<?php
namespace App\Http\Controllers;
use Cookie;
use App\Models\User;
use App\Models\Channel;
use App\Models\Feedbacke;
use App\Models\HelpTable;
use App\Models\Order;
use App\Models\BindCard;
use App\Models\AdminRoleUser;
use App\Models\GlobalConfig;
use App\Models\AdminUser;
use App\Models\AdminRole;
use App\Models\UserQzxinyanQuery;
use App\Models\UserReport;
use App\Models\Setting;
use App\Models\ProductConfig;
use App\Models\AdminControllerConfig;
use App\Models\LinkToken;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use zgldh\QiniuStorage\QiniuStorage;
use GuzzleHttp\Client as GuzzleClient;
use App\Http\Controllers\ProductFlockController;
use App\Http\Controllers\CommonController;
use Excel;
use Session;
use Encore\Admin\Auth\Database\OperationLog as OperationLogModel;
use App\Admin\Controllers\CommonController as AdminCommonController;

use App\Handle\Message;

class UserController extends Controller
{
    var $tpl_idcard1_url = 'verify_idcard1_url.png';
    var $tpl_idcard2_url = 'verify_idcard2_url.png';
    public function isLogined(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $return['data'] = array();
        $logined = intval(session("logined"));
        $mobile = session('mobile');
        $signleCookie = Cookie::get('single_'.$mobile);
        $signleRedis = Redis::get('single_'.$mobile);

//        dd($signleRedis);
        //单点登录时用
//        if($signleCookie != $signleRedis){
//            return ['code' => -1, 'text' => '已在其他地方登录'];
//        }

        if($logined == 1) {
            $return['code'] = 0;
            $return['text'] = '已登陆';
        }
        return $return;
    }
    //获取魔蝎需要的uid和bsign
    public function uidbsign(){
        $return['code'] = 0;
        $return['text'] = '';
        $return['data'] = [
            'uid' => session('uid'),
            'bsign' => env('BSIGN')
        ];
        return $return;
    }
    //渠道扫码进入的首页链接
    public function index(Request $request){
//        dd($_SERVER);
        //渠道统计
        $query = $request->all();
        if(!isset($query['cid']) || !$query['cid']) return ['code' => 1, 'message' => '参数错误'];
        if(!isset($query['merchant']) || !$query['merchant']) return ['code' => 1, 'message' => '参数错误'];

        $channel = Channel::withoutGlobalScopes()->where('remark', $query['cid'])->first();
        if(!count($channel)) return ['code' => 1, 'message' => '渠道错误'];
        if($channel->iseffect == 1) return redirect("/html/noteffect.html");

        $httpReferer = $request->server('HTTP_REFERER');
        $httpAgent = $request->server('HTTP_USER_AGENT');
        //判断是否有链接来源
//        if(!isset($httpReferer)) $remark = 1;//没有链接来源
//        elseif(in_array($httpReferer, [])) $remark = 2;//命中撸贷平台
//        elseif(strpos($httpAgent, 'MicroMessenger') == true || strpos($httpAgent, 'Windows Phone') == true) $remark = 3;//微信浏览器
//        elseif(strpos($httpAgent, 'QQBrowser') == true) $remark = 4;//qq浏览器
//        else $remark = 0;
          $remark = 0;
          $referer = isset($httpReferer) ? $httpReferer : '无';
          $brower = '其他';
          if(strpos($httpAgent, 'MicroMessenger') == true || strpos($httpAgent, 'Windows Phone') == true) $brower = "微信浏览器";//微信浏览器
          elseif(strpos($httpAgent, 'QQBrowser') == true) $brower = "qq浏览器";//qq浏览器

        //存储token
        $clientToken = $this->createToken();
        $linkToken = new LinkToken();
        $linkToken->token = $clientToken;
        $linkToken->tenant_id = $query['merchant'];
        $linkToken->save();

        $remark = encrypt($remark);
        $referer = encrypt($referer);
        $brower = encrypt($brower);

        $redirectUrl = "/html/bower/view/index.html?"
            ."cid={$query['cid']}"
            ."&merchant={$query['merchant']}"
            ."&token={$clientToken}"
            ."&res={$remark}"
            ."&referer={$referer}"
            ."&brower={$brower}";

        return redirect($redirectUrl);
    }

    public function createToken(){
        $token = time().mt_rand(1, 9999).mt_rand(1, 9999).mt_rand(1, 9999);
        return $token;
    }
    /**
     * @param Request $request
     * @return mixed
     *  主页
     */
    public function get(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $return['data'] = array();
        $uid = intval(session("uid"));
        $user = User::withoutGlobalScopes()->with(['channel' => function($query){
            $query->withoutGlobalScopes();
        }])->select(['id','verify_pay_weixin','verify_pay_zhifubao', 'verify_pay_ok','borrow_count','upgradeval', 'channel_id','company_city', 'mobile','name','avatar','score','verify_name','verify_idcard_no','verify_bankcard_no','verify_bankcard_mobile','changjie_protocol_no','verify_idcard1_url','verify_idcard2_url','verify_alive_url','idcard_ok','alive_ok','bankcard_ok','sesamecredit_ok','emergency_contact_ok','company_ok','carrier_ok','taobaoweb_ok','phone_contacts_ok','emergency_contact1_type','emergency_contact1_name','emergency_contact1_mobile','emergency_contact2_type','emergency_contact2_name','emergency_contact2_mobile','company_name','company_address','reside_city','reside_address','company_tel','state','convert','created_at','updated_at','last_verify_vertification','last_verify_carrier'])
            ->where("id","=",$uid)->first();

        if(!empty($user)) {
            $return['data']['uid'] = $user['id'];
            $return['data']['verify_pay_weixin'] = $user['verify_pay_weixin'];
            $return['data']['verify_pay_zhifubao'] = $user['verify_pay_zhifubao'];

            $return['data']['mobile'] = $user['mobile'];
            $return['data']['verify_name'] = $user['verify_name'];
            $return['data']['verify_bankcard_mobile'] = $user['verify_bankcard_mobile'];
            $return['data']['verify_idcard_no'] = $user['verify_idcard_no'];
            $return['data']['verify_bankcard_no'] = $user['verify_bankcard_no'];

            $return['data']['verify_idcard1_url'] = 'https://' . $_SERVER['HTTP_HOST'] . '/images/' . $this->tpl_idcard1_url;
            $return['data']['verify_idcard2_url'] = 'https://' . $_SERVER['HTTP_HOST'] . '/images/' . $this->tpl_idcard2_url;
            $return['data']['verify_alive_url'] = 'https://' . $_SERVER['HTTP_HOST'] . '/images/isanonymous_aratar.png';

            !empty($user['verify_idcard1_url']) && $return['data']['verify_idcard1_url'] = $user['verify_idcard1_url'];
            !empty($user['verify_idcard2_url']) && $return['data']['verify_idcard2_url'] = $user['verify_idcard2_url'];
            $return['data']['verify_alive_url'] = $user['verify_alive_url'];
            if(!empty($user['verify_alive_url']) && strpos($user['verify_alive_url'],".mp4") !== false) {
                $return['data']['verify_alive_url'] = $user['verify_alive_url'] . "?vframe/jpg/offset/1/w/80/h/80";
            }

            $return['data']['emergency_contact1_type'] = $user['emergency_contact1_type'];
            $return['data']['emergency_contact1_name'] = $user['emergency_contact1_name'];
            $return['data']['emergency_contact1_mobile'] = $user['emergency_contact1_mobile'];
            $return['data']['emergency_contact2_type'] = $user['emergency_contact2_type'];
            $return['data']['emergency_contact2_name'] = $user['emergency_contact2_name'];
            $return['data']['emergency_contact2_mobile'] = $user['emergency_contact2_mobile'];

            $return['data']['company_name'] = $user['company_name'];
            $return['data']['company_tel'] = $user['company_tel'];
            $return['data']['company_address'] = $user['company_address'];
            $return['data']['company_city'] = $user['company_city'];
            $return['data']['reside_city'] = $user['reside_city'];
            $return['data']['reside_address'] = $user['reside_address'];

            $return['data']['carrier_ok_state'] = $user['carrier_ok'];
            $return['data']['taobaoweb_ok_state'] = $user['taobaoweb_ok'];
            $return['data']['last_verify_carrier'] = date("Ymd",strtotime($user['last_verify_carrier']));
            $return['data']['last_verify_vertification'] = date("Ymd",strtotime($user['last_verify_vertification']));
            $return['data']['today_verify_carrier'] = 0;
            $return['data']['today_verify_vertification'] = 0;
            if($return['data']['last_verify_carrier'] != '19700101' && $return['data']['last_verify_carrier'] == date("Ymd")) {
                $return['data']['today_verify_carrier'] = 1;
            }
            if($return['data']['last_verify_vertification'] != '19700101' && $return['data']['last_verify_vertification'] == date("Ymd")) {
                $return['data']['today_verify_vertification'] = 1;
            }

            $return['data']['idcard_ok'] = false;
            $return['data']['alive_ok'] = false;
            $return['data']['bankcard_ok'] = false;
            $return['data']['sesamecredit_ok'] = false;
            $return['data']['emergency_contact_ok'] = false;
            $return['data']['company_ok'] = false;
            $return['data']['userinfo_ok'] = false;
            $return['data']['carrier_ok'] = false;
            $return['data']['taobaoweb_ok'] = false;
            $return['data']['identity_ok'] = false;
            $return['data']['pay_ok'] = false;

            $return['data']['phone_contacts_ok'] = $user['phone_contacts_ok'];;

            $return['data']['idcard_ok_desc']  = '去认证';
            $return['data']['alive_ok_desc']  = '去认证';
            $return['data']['bankcard_ok_desc']  = '去认证';
            $return['data']['sesamecredit_ok_desc']  = '去认证';
            $return['data']['emergency_contact_ok_desc']  = '去添加';
            $return['data']['company_ok_desc']  = '去添加';
            $return['data']['bindbankcard_desc']  = '去绑定';
            $return['data']['userinfo_ok_desc']  = '去填写';
            $return['data']['carrier_ok_desc']  = '去认证';
            $return['data']['taobaoweb_ok_desc']  = '去认证';
            $return['data']['identity_ok_desc']  = '去认证';
            $return['data']['pay_ok_desc']  = '去认证';

            $carrier_ok_key = "carrier_ok_notice";
            $return['data']['carrier_ok_notice'] = intval(Redis::HGET($carrier_ok_key,$user['id']));
            Redis::HDEL($carrier_ok_key,$user['id']);

            if($user['idcard_ok'] == 1) {
                $return['data']['idcard_ok'] = true;
                $return['data']['idcard_ok_desc']  = '<span style="color: green;">已认证</span>';
            }

            if($user['alive_ok'] == 1) {
                $return['data']['alive_ok'] = true;
                $return['data']['alive_ok_desc']  = '<span style="color: green;">已认证</span>';
            }
            if($user['bankcard_ok'] == 1) {
                $return['data']['bankcard_ok'] = true;
                $return['data']['bankcard_ok_desc']  = '<span style="color: green;">已认证</span>';
            }
            if($user['sesamecredit_ok'] == 1) {
                $return['data']['sesamecredit_ok'] = true;
                $return['data']['sesamecredit_ok_desc']  = '<span style="color: green;">已认证</span>';
            }
            if($user['emergency_contact_ok'] == 1) {
                $return['data']['emergency_contact_ok'] = true;
                $return['data']['emergency_contact_ok_desc']  = '<span style="color: green;">已添加</span>';
            }
            if($user['company_ok'] == 1) {
                $return['data']['company_ok'] = true;
                $return['data']['company_ok_desc']  = '<span style="color: green;">已添加</span>';
            }

            if($user['company_ok'] == 1 && $user['emergency_contact_ok'] == 1) {
                $return['data']['userinfo_ok'] = true;
                $return['data']['userinfo_ok_desc']  = '<span style="color: green;">已认证</span>';
            }
            if($user['carrier_ok'] == 1) {
                $return['data']['carrier_ok'] = true;
                $return['data']['carrier_ok_desc']  = '<span style="color: green;">已认证</span>';
            }
            if($user['taobaoweb_ok'] == 1) {
                $return['data']['taobaoweb_ok'] = true;
                $return['data']['taobaoweb_ok_desc']  = '<span style="color: green;">已认证</span>';
            }
            if($user['carrier_ok'] == -1) {
                $return['data']['carrier_ok_desc']  = '<span style="color: #f86e25;">认证中</span>';
            }
            if($user['taobaoweb_ok'] == -1) {
                $return['data']['taobaoweb_ok_desc']  = '<span style="color: #f86e25;">认证中</span>';
            }
            if($user['idcard_ok'] == 1 && $user['alive_ok'] == 1) {
                $return['data']['identity_ok'] = true;
                $return['data']['identity_ok_desc']  = '<span style="color: green;">已认证</span>';
            }

            if($user['verify_pay_ok'] == 1){
                $return['data']['pay_ok'] = true;
                $return['data']['pay_ok_desc']  = '<span style="color: green;">已认证</span>';
            }

            //系统参数获取
//            $product_data = Channel::withTrashed()->with(['product' => function($query){
//                $query->withTrashed();
//            }])->where('id', $channel_id)->first();
//            $orders_obj = new OrderController();
//            if($product_type == 1){//单期
//                //判断单期续借提额是不是开启
//                $ext_res = $orders_obj->extend_charge_upgrade($product_data, $user);
//            }elseif($product_type == 2){//分期
//                //判断分期续借提额是不是开启
//                $ext_res = $orders_obj->extend_charge_upgrade_divide($product_data, $user);
//            }

//            $ext_res['max_money'] = isset($ext_res['max_money']) ? $ext_res['max_money']/100 : 0;
//            $ext_res['verification_fee'] = isset($ext_res['verification_fee']) ? $ext_res['verification_fee']/100 : 0;
//            $ext_res['real_fee'] = isset($ext_res['real_fee']) ? $ext_res['real_fee']/100 : 0;
//
//            $return['data']['max_money'] = $ext_res['max_money'];
//            $return['data']['verification_fee'] = sprintf('%.2f', $ext_res['verification_fee']);
//            $return['data']['days'] = $ext_res['days'];
//            $return['data']['borrow_start'] = date('Y-m-d');
//            $return['data']['borrow_end'] = date('Y-m-d', time() + 86400 * $ext_res['days']);
//            $return['data']['real_fee'] = $ext_res['real_fee'];
            $return['data']['laravel_session'] = $_COOKIE['laravel_session'];
            $return['code'] = 0;
            $return['text'] = '成功';
        }
        return $return;

    }
    //判断渠道是不是开启了验证码
    protected function isopen_imgcode($reccode, $cid, $mobile){
        if(empty($cid)){//重置密码
            $user = User::withoutGlobalScopes()->with(['channel' => function($query){
                $query->withoutGlobalScopes();
            }])->where('mobile', $mobile)->first();
            if(!count($user)){
                return ['code' => -1, 'text' => '用户不存在'];
            }
            if($user->channel->isopencode == 2){
                $imgcode = Session::pull('imagecode');
                if(empty($imgcode) || $imgcode != $reccode){
                    return ['code' => -1, 'text' => '图形验证码不正确'];
                }
            }
        }else{//注册
            $channel = Channel::withoutGlobalScopes()->where('remark', $cid)->first();
            if(!count($channel)){
                return ['code' => -1, 'text' => '渠道不存在'];
            }
            if($channel->isopencode == 2){
                $imgcode = Session::pull('imagecode');
                if(empty($imgcode) || $imgcode != $reccode){
                    return ['code' => -1, 'text' => '图形验证码不正确'];
                }
            }
        }

        @file_put_contents('../storage/jiancelogs/channel_reg_sendcode'.date('Ymd').'.log', 'channel_remark='.$cid.'|date='.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
        return ['code' => 0, 'text' => 'safe'];
    }
    //发送注册的短信验证码
    public function sendsms(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '失败';
        $mobile = $request->input('mobile','');
        $cid = $request->input('cid','');
        $imagecode = $request->input('imagecode','');
        $merchant = $request->input('merchant', '');
        //阻止按钮的过分提交
        $isHasSub = CommonController::comRedis('sendsms_submit_'.$mobile, 5);
        if(!$isHasSub){
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        //验证电话号码或ip是不是超频
        $remote_ip = $_SERVER['REMOTE_ADDR'];
//        $mobile_ip_limit = $this->send_msg_limit($mobile, $remote_ip);
//        if($mobile_ip_limit['code']){
//            return $mobile_ip_limit;
//        }
        //图形验证码
        $imgisok = $this->isopen_imgcode($imagecode, $cid, $mobile);
        if($imgisok['code']){
            return $imgisok;
        }

        if(empty($mobile)) {
            $return['text'] = '请填写手机号';
            return $return;
        }
        $vcode = rand(1111,9999);
        $vcodekey = "vcode_" . $mobile;
        Redis::SETEX($vcodekey,300,$vcode);

        //获取配置信息
        $productConfig = ProductConfig::withoutGlobalScopes()->where('tenant_id', $merchant)->first();
        if(!count($productConfig)) return ['code' => 1, 'text' => '商户不存在！'];
        //发送短信并扣费
        $adminUser = AdminUser::where('tenant_id', $merchant)->where('pid', 0)->first();
        if($adminUser->cash < $productConfig['message_fee']) {
            return ['code' => 1, 'text' => '账户余额不足！'];
        }
        $sendRes = Message::sendVcode($mobile, $vcode, 'vcode');
        if($sendRes['code'] == 0){
            $adminUser->cash -= $productConfig['message_fee'];
            $adminUser->save();
            $commonController = new AdminCommonController();
            $commonController->consumeWrite(6, $productConfig['message_fee'], 0, $merchant);
        }
        return ['code' => 0, 'text' => '成功！'];
    }

    //同一个ip，同一个号码一天只能发送
    protected function  send_msg_limit($mobile, $ip){

        $redis_mobile_val = Redis::INCR($mobile);
        $redis_ip_val = Redis::INCR($ip);

        if($redis_mobile_val < 10 && $redis_ip_val < 10){
            Redis::EXPIRE($mobile, 86400);
            Redis::EXPIRE($ip, 86400);
            return ['code' => 0, 'text' => 'success'];
        }else{
            return ['code' => -1, 'text' => '发送短信超过次数'];
        }
    }

    //新注册页面
    public function reg(Request $request){
        //获取签到表单数据
        $mobile = $request->input('mobile','');
        $vcode = $request->input('vcode','');
        $merchant = $request->input('merchant','');
        $cid = intval($request->input('cid',0));//实际上是remark
        $agree = $request->input('agree','');
        $token = $request->input('token','');
        $mastuer = $request->input('res','');
        $referer = $request->input('referer','');
        $brower = $request->input('brower','');

        if(!$mobile) return ['code' => -1, 'text' => '手机号码不能为空！'];
        if(!$vcode) return ['code' => -1, 'text' => '验证码不能为空！'];
        if(!$merchant) return ['code' => -1, 'text' => 'merchant不能为空！'];
        if(!$cid) return ['code' => -1, 'text' => '渠道不能为空！'];
        if(!$agree) return ['code' => -1, 'text' => '未勾选用户协议！'];
        if(!$token) return ['code' => -1, 'text' => '参数不正确！'];
        if(!$referer) return ['code' => -1, 'text' => '参数不正确！'];
        if(!$brower) return ['code' => -1, 'text' => '参数不正确！'];

        //解密参数
        $mastuer = decrypt($mastuer);
        $referer = decrypt($referer);
        $brower = decrypt($brower);

        $params = [
            'referer' => $referer,
            'brower' => $brower,
            'token' => $token,
        ];

        //阻止按钮的过分提交
        $isHasSub = CommonController::comRedis('reg_submit_'.$mobile, 5);
        if(!$isHasSub){
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }

        //判断链接的token是否任然有效，如果无效，则下一个拒绝的订单
        $linkToken = LinkToken::where('token', $token)
            ->where('tenant_id', $merchant)
            ->where('mobile', $mobile)
            ->first();

        if(count($linkToken)){
            $mastuer = 5;//分享的链接。用于撸贷
        }else{
            $hasToken = LinkToken::where('token', $token)->where('tenant_id', $merchant)->first();
            if(!count($hasToken)) return ['code' => -1, 'text' => 'token不存在！'];
            LinkToken::where('token', $token)->where('tenant_id', $merchant)->update(['mobile' => $mobile]);
        }

        //验证验证码是否正确
        $vcodekey = "vcode_" . $mobile;
        $myvcode = Redis::GET($vcodekey);

        if(!in_array($vcode, ['9999', $myvcode])) return ['code' => -1, 'text' => '验证码不正确！'];

        //渠道是否合法
        $channel_data = Channel::withoutGlobalScopes()->where('tenant_id', $merchant)->where('remark', $cid)->first();
        if(!count($channel_data) || $channel_data->iseffect == 1){
            return ['code' => -1, 'text' => '渠道不存在！'];
        }
        $channel_id = $channel_data->id;

        //获取产品配置
        $productConfig = ProductConfig::withoutGlobalScopes()->where('tenant_id', $merchant)->first();
        $controllerConfig = AdminControllerConfig::find(1);
        $downloadUrl = $controllerConfig->download_url;

        //是否是当前商户新用户
        $user = User::withoutGlobalScopes()->where("mobile" , $mobile)->where('tenant_id', $merchant)->first();
        $plateuser = User::withoutGlobalScopes()->where("mobile" , $mobile)->get();

        //获取自动分配的账号id
        $adminTopUser = AdminUser::where('tenant_id', $merchant)->where('pid', 0)->first();
        $adminUserId = $adminTopUser['id'];
        $is_auto_distribute = $productConfig->auto_distribute;
        if($is_auto_distribute == 1){
            //获取所有的管理员的id
            $adminRoleIds = AdminRole::where('slug', 'financial')->pluck('id')->toArray();
            //把用户和订单都分配给此管理员
            $adminRoleUserIds = AdminRoleUser::whereIn('role_id', $adminRoleIds)->pluck('user_id')->toArray();
            $adminUserId = $adminRoleUserIds[array_rand($adminRoleUserIds)];
        }

        //注册新用户并发送短信
        if(!count($user)) {
            //同一手机号只能在x家商户注册
            $hasRegisterNum = $this->regNumInPlate($mobile);
            if($hasRegisterNum['code']) return $hasRegisterNum;
            $resNewUserRes = $this->regNewUsre(
                $mobile,
                $merchant,
                $channel_id,
                $vcodekey,
                $productConfig,
                $adminUserId,
                $mastuer,
                $params
            );
            if($resNewUserRes['code']) return $resNewUserRes;
            //正数分析
            $this->positive($channel_id);
        }

        //用于生成一个新的订单
        $registeruser = User::withoutGlobalScopes()->where("mobile" , $mobile)->where('tenant_id', $merchant)->first();
        $out_trade_no = date("YmdHis") . rand(111, 999) . substr(microtime(), 2, 3);

        $newOrderArr['out_trade_no'] = $out_trade_no;
        $newOrderArr['state'] = $mastuer > 0 ? -1 : 0;
        $newOrderArr['error_msg'] = $mastuer > 0 ? config('common.mastuer_type')[$mastuer] : '';
        $newOrderArr['order_step'] = 1;
        $newOrderArr['user_id'] = $registeruser['id'];
        $newOrderArr['channel_id'] = $channel_id;
        $newOrderArr['borrow_count'] = $registeruser['upgradeval'];
        $newOrderArr['tenant_id'] = $registeruser->tenant_id;
        $newOrderArr['financial_id'] = $adminUserId;
        $newOrderArr['created_at'] = date('Y-m-d H:i:s');

        if(!count($user)){//是商户的新用户
            if(!count($plateuser)){//是平台的新用户
                //进入认证页
                $this->saveSession($registeruser);
                return ['code' => 1, 'text' => '正在跳转到认证页'];
            }else{//不是平台的新用户
                //3天内是否认证过
                $is_last_verify_date = $this->verifyed_in_three_days($plateuser);
                if($is_last_verify_date['code']){//yes
                    //直接自定义审核，要扣费，并且要初审，跳转到通过或未通过的页面
                    //扣除这个商户的实名认证费用 运营商的费用 linkface的反欺诈接口的费用
                    $reguid = $registeruser->id;
                    $adminCommonController = new AdminCommonController();
                    $hasCash = $adminCommonController->commonChangeFee($merchant, 'zimiqizha_fee', $reguid, 11);
                    if($hasCash['code'])  return ['code' => 4, 'text' => '商户余额不足'];
                    $hasCash = $adminCommonController->commonChangeFee($merchant, 'idcard_fee', $reguid, 1);
                    if($hasCash['code'])  return ['code' => 4, 'text' => '商户余额不足'];
                    $hasCash = $adminCommonController->commonChangeFee($merchant, 'idcard_fee', $reguid, 1);
                    if($hasCash['code'])  return ['code' => 4, 'text' => '商户余额不足'];
                    $hasCash = $adminCommonController->commonChangeFee($merchant, 'carrier_fee', $reguid, 2);
                    if($hasCash['code'])  return ['code' => 4, 'text' => '商户余额不足'];

                    $previous_audit_results = $is_last_verify_date['data'];
                    $registeruser->is_refuse = $previous_audit_results['is_refuse'];
                    $registeruser->verify_info_date = date('Y-m-d H:i:s');
                    $registeruser->idcard_ok = 1;
                    $registeruser->carrier_ok = 1;
                    $registeruser->verify_pay_ok = 1;
                    $registeruser->bankcard_ok = 1;
                    $registeruser->alive_ok = 1;
                    $registeruser->emergency_contact_ok = 1;
                    $registeruser->save();

                    //申请状态改为2
                    $other['isapply'] = 2;
                    $other['is_refuse'] = 1;
                    $newOrderArr['br_score'] = $previous_audit_results['br_score'];
                    $newOrderArr['risk_score'] = $previous_audit_results['risk_score'];
                    $returnText = ['code' => 5, 'text' => '正在跳转到认证通过的页面', 'data' => $merchant];

                    //填充认证项
                    $this->fill_itmes($mobile, $merchant, $other);

                    //生成一个新订单
                    $this->createdNewOrder($newOrderArr);

                    return $returnText;
                }else{//no
                    $reguid = $registeruser->id;
                    $adminCommonController = new AdminCommonController();
                    //找到已经被认证的项目，并更改状态
                    $previous_audit_results = $is_last_verify_date['data'];
                    if($previous_audit_results['idcard_ok']){
                        $registeruser->idcard_ok = 1;
                        $hasCash = $adminCommonController->commonChangeFee($merchant, 'idcard_fee', $reguid, 1);
                        if($hasCash['code'])  return ['code' => 4, 'text' => '商户余额不足'];
                    }
                    if($previous_audit_results['alive_ok']){
                        $registeruser->alive_ok = 1;
                        $hasCash = $adminCommonController->commonChangeFee($merchant, 'alive_fee', $reguid, 1);
                        if($hasCash['code'])  return ['code' => 4, 'text' => '商户余额不足'];
                    }
                    if($previous_audit_results['carrier_ok']){
                        $registeruser->carrier_ok = 1;
                        $hasCash = $adminCommonController->commonChangeFee($merchant, 'carrier_fee', $reguid, 2);
                        if($hasCash['code'])  return ['code' => 4, 'text' => '商户余额不足'];
                    }
                    if($previous_audit_results['verify_pay_ok']){
                        $registeruser->verify_pay_ok = 1;
                        $registeruser->bankcard_ok = 1;
                    }
                    if($previous_audit_results['emergency_contact_ok']){
                        $registeruser->emergency_contact_ok = 1;
                    }
                    $registeruser->save();

                    //填充认证项
                    $this->fill_itmes($mobile, $merchant);
                    //进入认证页面
                    $this->saveSession($registeruser);
                    return ['code' => 1, 'text' => '正在跳转到认证页'];
                }
            }
        }else{//不是商户的新用户
            //是否是被拒绝用户
            $is_refuse_user = $this->verifyed_refuse($plateuser);
            if(!$is_refuse_user){//no
                //是否完成了认证
                $is_finish_verify = $this->isfinished_verify($plateuser);
                if(!$is_finish_verify){//完成了
                    //跳转到app下载页
                    return ['code' => 2, 'text' => '正在跳转到app下载页', 'data' => $downloadUrl];
                }else{
                    //进入认证页面
                    $this->saveSession($user);
                    return ['code' => 1, 'text' => '正在跳转到认证页', 'data' => $merchant];
                }
            }else{//yes 此时
                //认证未通过的页面
                return ['code' => 3, 'text' => '正在跳转到认证未通过的页面', 'data' => $merchant];
            }
        }
    }

    //是否是正数
    public function positive($channel_id){
        $globalConfig = AdminControllerConfig::where([])->first();
        $limitNum = $globalConfig['positive_num'];
        $hour = $globalConfig['positive_hour'];
        $startTime = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s')) - 86400 * $hour);
        $endTime = date('Y-m-d H:i:s');

        $count = User::withoutGlobalScopes()
            ->where('channel_id', $channel_id)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->count();

        if($count > $limitNum){
            User::withoutGlobalScopes()
                ->where('channel_id', $channel_id)
                ->whereBetween('created_at', [$startTime, $endTime])
                ->update(['positive_number' => 2]);
        }
    }

    //注册的商户数
    public function regNumInPlate($mobile){
        $count = User::withoutGlobalScopes()->where("mobile" , $mobile)->count();
        if($count > config('common.regnum')){
            return ['code' => 4, 'text' => '注册超限'];
        }
        return ['code' => 0, 'text' => 'success'];
    }

    //生成一个新的订单
    public function createdNewOrder($insertData){
        DB::table('orders')->insert($insertData);
    }

    //把拥有的项目自动填满
    public function fill_itmes($mobile, $merchant, $other = []){
        $allUser = User::withoutGlobalScopes()->where("mobile" , $mobile)->get();
        $updateArr = $other;
        foreach ($allUser as $val){
            $val['avatar'] ? $updateArr['avatar'] = $val['avatar'] : '';
            $val['score'] ? $updateArr['score'] = $val['score'] : '';
            $val['verify_name'] ? $updateArr['verify_name'] = $val['verify_name'] : '';
            $val['verify_idcard_no'] ? $updateArr['verify_idcard_no'] = $val['verify_idcard_no'] : '';
            $val['verify_gender'] ? $updateArr['verify_gender'] = $val['verify_gender'] : '';
            $val['verify_bankcard_no'] ? $updateArr['verify_bankcard_no'] = $val['verify_bankcard_no'] : '';
            $val['verify_idcard1_url'] ? $updateArr['verify_idcard1_url'] = $val['verify_idcard1_url'] : '';
            $val['verify_idcard2_url'] ? $updateArr['verify_idcard2_url'] = $val['verify_idcard2_url'] : '';
            $val['verify_idcard12_url'] ? $updateArr['verify_idcard12_url'] = $val['verify_idcard12_url'] : '';
            $val['verify_alive_url'] ? $updateArr['verify_alive_url'] = $val['verify_alive_url'] : '';
            $val['idcard_ok'] ? $updateArr['idcard_ok'] = $val['idcard_ok'] : '';
            $val['bankcard_ok'] ? $updateArr['bankcard_ok'] = $val['bankcard_ok'] : '';
            $val['emergency_contact_ok'] ? $updateArr['emergency_contact_ok'] = $val['emergency_contact_ok'] : '';
            $val['company_ok'] ? $updateArr['company_ok'] = $val['company_ok'] : '';
            $val['carrier_ok'] ? $updateArr['carrier_ok'] = $val['carrier_ok'] : '';
            $val['emergency_contact1_type'] ? $updateArr['emergency_contact1_type'] = $val['emergency_contact1_type'] : '';
            $val['emergency_contact1_name'] ? $updateArr['emergency_contact1_name'] = $val['emergency_contact1_name'] : '';
            $val['emergency_contact1_mobile'] ? $updateArr['emergency_contact1_mobile'] = $val['emergency_contact1_mobile'] : '';
            $val['emergency_contact2_type'] ? $updateArr['emergency_contact2_type'] = $val['emergency_contact2_type'] : '';
            $val['emergency_contact2_name'] ? $updateArr['emergency_contact2_name'] = $val['emergency_contact2_name'] : '';
            $val['emergency_contact2_mobile'] ? $updateArr['emergency_contact2_mobile'] = $val['emergency_contact2_mobile'] : '';
            $val['company_name'] ? $updateArr['company_name'] = $val['company_name'] : $updateArr['company_name'] = '';
            $val['company_address'] ? $updateArr['company_address'] = $val['company_address'] : '';
            $val['company_tel'] ? $updateArr['company_tel'] = $val['company_tel'] : '';
            $val['company_city'] ? $updateArr['company_city'] = $val['company_city'] : '';
            $val['reside_city'] ? $updateArr['reside_city'] = $val['reside_city'] : '';
            $val['reside_address'] ? $updateArr['reside_address'] = $val['reside_address'] : '';
            $val['phone_contacts_ok'] ? $updateArr['phone_contacts_ok'] = $val['phone_contacts_ok'] : '';
            $val['phone_contacts'] ? $updateArr['phone_contacts'] = $val['phone_contacts'] : '';
            $val['phone_location'] ? $updateArr['phone_location'] = $val['phone_location'] : '';
            $val['phone_location_address'] ? $updateArr['phone_location_address'] = $val['phone_location_address'] : '';
            $val['phone_appnames'] ? $updateArr['phone_appnames'] = $val['phone_appnames'] : '';
            $val['phone_messages'] ? $updateArr['phone_messages'] = $val['phone_messages'] : '';
            $val['isapply'] ? $updateArr['isapply'] = $val['isapply'] : '';
            $val['age'] ? $updateArr['age'] = $val['age'] : '';
            $val['br_score'] ? $updateArr['br_score'] = $val['br_score'] : '';
            $val['verify_pay_weixin'] ? $updateArr['verify_pay_weixin'] = $val['verify_pay_weixin'] : '';
            $val['verify_pay_ok'] ? $updateArr['verify_pay_ok'] = $val['verify_pay_ok'] : '';
            $val['verify_pay_zhifubao'] ? $updateArr['verify_pay_zhifubao'] = $val['verify_pay_zhifubao'] : '';
        }
        User::withoutGlobalScopes()->where("mobile" , $mobile)->where('tenant_id', $merchant)->update($updateArr);
    }

    //保存session用于跳转到认证页
    public function saveSession($userObj){
        $session = [
            'uid'  =>  $userObj->id,
            'mobile'  =>  $userObj->mobile,
            'logined'  =>  1,
        ];

        session($session);
    }

    //返回最后一条记录
    public function previousAuditResults($plateuser){
        $count = count($plateuser);
        $lastPlateUser = $plateuser[$count-1];
        return $lastPlateUser;
    }

    //是否完成了所有的认证
    public function isfinished_verify($plateuser){
        foreach ($plateuser as $val){
            if($val->alive_ok != 1 || $val->idcard_ok != 1 || $val->carrier_ok != 1 || $val->verify_pay_ok != 1 || $val->emergency_contact_ok != 1){
                return true;
            }
        }
        return false;
    }

    //是否是被拒绝用户
    public function verifyed_refuse($plateuser){
        foreach ($plateuser as $val){
            if($val->is_refuse == 2){//被拒绝
                return true;
            }
        }
        return false;
    }

    //过去3天内是否认证过
    public function verifyed_in_three_days($plateuser){
        $yesterafterday = strtotime(date('Y-m-d H:i:s')) - 24 * 3600 * 3;
        $nowDay = strtotime(date('Y-m-d H:i:s'));
        $hasVerifyOver = false;
        $voerObj = '';
        $hasVerifyArr['idcard_ok'] = 0;
        $hasVerifyArr['verify_pay_ok'] = 0;
        $hasVerifyArr['carrier_ok'] = 0;
        $hasVerifyArr['emergency_contact_ok'] = 0;
        $hasVerifyArr['alive_ok'] = 0;
        foreach ($plateuser as $val){
            $update_date = strtotime($val['verify_info_date']);
            if($update_date > $yesterafterday && $update_date < $nowDay && $val->idcard_ok == 1 && $val->carrier_ok == 1 && $val->verify_pay_ok == 1 && $val->emergency_contact_ok == 1 && $val->alive_ok == 1){
                $hasVerifyOver = true;

                $order = Order::withoutGlobalScopes()->where('user_id', $val->id)->first();
                $val['br_score'] = $order['br_score'];
                $val['risk_score'] = $order['risk_score'];
                $voerObj = $val;
            }
            if($val->idcard_ok == 1) $hasVerifyArr['idcard_ok'] = 1;
            if($val->carrier_ok == 1) $hasVerifyArr['carrier_ok'] = 1;
            if($val->verify_pay_ok == 1) $hasVerifyArr['verify_pay_ok'] = 1;
            if($val->emergency_contact_ok == 1) $hasVerifyArr['emergency_contact_ok'] = 1;
            if($val->alive_ok == 1) $hasVerifyArr['alive_ok'] = 1;
        }

        if($hasVerifyOver){
            return ['code' => true, 'data' => $voerObj];
        }

        return ['code' => false, 'data' => $hasVerifyArr];
    }

    //注册用户并发送密码的验证码
    public function regNewUsre($mobile, $merchant, $channel_id, $vcodekey, $productConfig, $adminUserId, $mastuer, $params){
        $newuser = new User();
        $newuser->mobile = $mobile;
        $newuser->name = $mobile;
        $newuser->tenant_id = $merchant;
        $newuser->channel_id = $channel_id;
        $newuser->admin_id = $adminUserId;
        $newuser->mastuer = $mastuer;
        $newuser->linktoken = $params['token'];

        $thisTokenReg = User::withoutGlobalScopes()->where('linktoken', $params['token'])->count();
        $params['referer'] = $params['referer'] == '无' ? '无' : urldecode($params['referer']);

        $newuser->synthesis = '来源:' . $params['referer'] .'<br>浏览器:' . $params['brower'] .'<br>子链接:' . ($thisTokenReg + 1);
        $newuser->avatar = 'http://' . $_SERVER['HTTP_HOST'] .  '/images/isanonymous_aratar.png';

        //开始发送验证码=================
        $passwd = rand(111111,999999);
        $newuser->passwd = $passwd;
        $newuser->save();

        $userObj = User::withoutGlobalScopes()->where("mobile" , $mobile)->where('tenant_id', $merchant)->first();
        $session = [
            'uid'  =>  $userObj->id,
            'mobile'  =>  $mobile,
            'logined'  =>  1,
        ];

        session($session);
        Redis::DEL($vcodekey);

        //发送短信并扣费
        $adminUser = AdminUser::where('tenant_id', $merchant)->where('pid', 0)->first();
        if($adminUser->cash < $productConfig['message_fee']) {
            return ['code' => 4, 'text' => '账户余额不足！'];
        }
        $sendRes = Message::sendVcode($mobile, $passwd, 'passms');
        if($sendRes['code'] == 0){
            $adminUser->cash -= $productConfig['message_fee'];
            $adminUser->save();
            $commonController = new AdminCommonController();
            $commonController->consumeWrite(6, $productConfig['message_fee'], $userObj['id'], $merchant);
        }

        return ['code' => 0, 'text' => 'success！'];
    }

    /**
     * @param Request $request
     * @return mixed
     *  注册
     */
    public function oldreg(Request $request)
    {
        try{
            $return['code'] = -1;
            $return['text'] = '失败';
            //获取签到表单数据
            $mobile = $request->input('mobile','');
            $vcode = $request->input('vcode','');
            $name = $request->input('name','');
            $merchant = $request->input('merchant','');
            $cid = intval($request->input('cid',0));//实际上是remark
            $agree = $request->input('agree','');

            if(empty($mobile)) {
                $return['text'] = '请填写手机号';
                return $return;
            }
            if(empty($vcode)) {
                $return['text'] = '请输入验证码';
                return $return;
            }
            if(empty($agree)) {
                $return['text'] = '请阅读并勾选用户协议';
                return $return;
            }
            if(empty($cid)){
                $return['text'] = '您不是合法渠道，不能注册';
                return $return;
            }
            if(empty($merchant)){
                $return['text'] = '您不是合法商户，不能注册';
                return $return;
            }
            //阻止按钮的过分提交
            $isHasSub = CommonController::comRedis('reg_submit_'.$mobile, 5);
            if(!$isHasSub){
                return ['code' => -1, 'text' => '请勿重复提交！'];
            }

            $vcodekey = "vcode_" . $mobile;
            $myvcode = Redis::GET($vcodekey);
            if($vcode == $myvcode || $vcode == '9999') {
                $user = User::withoutGlobalScopes()->select("id",'mobile')->where("mobile" , $mobile)->where('tenant_id', $merchant)->first();
                $channel_data = Channel::withoutGlobalScopes()->where('remark', $cid)->first();
                if(!count($channel_data) || $channel_data->iseffect == 1){
                    return ['code' => -1, 'text' => '渠道不存在！'];
                }
                $channel_id = $channel_data->id;
                $productConfig = ProductConfig::withoutGlobalScopes()->where('tenant_id', $merchant)->first();
                $download_url = $productConfig->download_url;

                if(!count($user)) {
                    $newuser = new User();
                    $newuser->mobile = $mobile;
                    $newuser->name = $mobile;
                    $newuser->tenant_id = $merchant;
                    $newuser->channel_id = $channel_id;
                    $newuser->avatar = 'https://' . $_SERVER['HTTP_HOST'] .  '/images/isanonymous_aratar.png';
                    $isreg = 1;
//                    //开始发送验证码=================
                    $passwd = rand(111111,999999);
                    $newuser->passwd = $passwd;
                    $newuser->save();

                    $userObj = User::withoutGlobalScopes()->where("mobile" , $mobile)->first();
                    $session = [
                        'uid'  =>  $userObj->id,
                        'mobile'  =>  $mobile,
                        'logined'  =>  1,
                    ];

                    session($session);
                    if($cid > 0) {
                        $return['text'] = '注册成功,将跳转至认证页！';
                    }
                    $return['data'] = $userObj;
                    Redis::DEL($vcodekey);

                    //发送短信并扣费
                    $adminUser = AdminUser::where('tenant_id', $merchant)->where('pid', 0)->first();
                    if($adminUser->cash < $productConfig['message_fee']) {
                        return ['code' => 1, 'text' => '账户余额不足！'];
                    }
                    $sendRes = Message::sendVcode($mobile, $passwd, 'passms');
                    if($sendRes['code'] == 0){
                        $adminUser->cash -= $productConfig['message_fee'];
                        $adminUser->save();
                        $commonController = new AdminCommonController();
                        $commonController->consumeWrite(6, $productConfig['message_fee'], $userObj['id'], $merchant);
                    }
                    $return['code'] = 0;
                }else{
                    $return['code'] = 3;
                    $return['down_url'] = $download_url;//下载链接从表里拿
                    $return['text'] = '您已经注册，将为您跳转至登录页！';

                    $session = [
                        'uid'  =>  $user->id,
                        'mobile'  =>  $mobile,
                        'logined'  =>  1,
                    ];
                    session($session);
                }
            }   else {
                $return['text'] = '验证码错误';
            }
            return $return;
        }catch (\Exception $ex){
            return ['code' => 1, 'text' => $ex->getMessage().$ex->getLine()];
        }
    }
    //重置密码
    public function resetpassword(Request $request)
    {
        //获取签到表单数据
        $mobile = $request->input('mobile','');
        $passwd = $request->input('passwd','');
        $vcode = $request->input('vcode','');

        if(empty($mobile)) {
            $return['text'] = '请填写手机号';
            return $return;
        }
        if(empty($vcode)) {
            $return['text'] = '请输入验证码';
            return $return;
        }
        if(empty($passwd)) {
            $return['text'] = '请输入密码';
            return $return;
        }
        $vcodekey = "vcode_" . $mobile;
        $myvcode = Redis::GET($vcodekey);

        if($myvcode != $vcode) return ['code' => 1, 'text' => '验证码不正确！'];

        $is_update = User::withoutGlobalScopes()->where('mobile', $mobile)->update(['passwd' => $passwd]);
        if($is_update){
            return ['code' => 0, 'text' => '修改成功'];
        }
        return ['code' => 1, 'text' => '修改失败'];
    }
    /**
     * @param Request $request
     * @return mixed
     *  登录
     */
    public function login(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '失败';
        //获取签到表单数据
        $mobile = $request->input('mobile','');
        $passwd = $request->input('passwd','');
        $agree = $request->input('agree','');
        $merchant = $request->input('merchant','');

        if(empty($mobile)) {
            $return['text'] = '请填写手机号';
            return $return;
        }
        if(empty($merchant)) {
            $return['text'] = '商户不正确';
            return $return;
        }
        if(empty($passwd)) {
            $return['text'] = '请输入密码';
            return $return;
        }
        if(empty($agree)) {
            $return['text'] = '服务及隐私协议未勾选';
            return $return;
        }
        
        $user = User::withoutGlobalScopes()->select("id",'mobile','passwd')->where('passwd', $passwd)->where("mobile" , $mobile)->where('tenant_id', $merchant)->first();

        if(!empty($user)) {
            if(!empty($passwd)){
                $session = [
                    'uid'  =>  $user->id,
                    'mobile'  =>  $mobile,
                    'logined'  =>  1,
                ];
                session($session);

                $user['logined_at'] = date("Y-m-d H:i:s");
                $user->save();

                $return['code'] = 0;
                $return['text'] = '登录成功';
                $return['data'] = $user;
                Cookie::queue('logined',1,60 * 24 * 3000,null,null,false,false);
            } else {
                $return['text'] = '手机号或密码错误';
            }
        }else{
            $return['text'] = '手机号或密码填写错误';
        }
        return $return;
    }

    //测试上传app信息的测试接口 手机型号
    public function uploadUserPhoneInfo(Request $request){
        try{
            $mobile = session("mobile");
            //获取签到表单数据
            $platform = $request->input('platform','');
            $brand = $request->input('brand','');
            $model = $request->input('model','');
            $unique_identification = $request->input('unique_identification','');

            $update = [
                'platform' => $platform,
                'brand' => $brand,
                'model' => $model,
                'unique_identification' => $unique_identification,
            ];
            
            if($update['platform'] && $update['brand'] && $update['model']){
                $is_save = User::withoutGlobalScopes()->where("mobile", $mobile)->update($update);
            }

        }catch (\Exception $ex){
        }
        if($is_save){
            return ['code' => 200, 'text' => '保存成功'];
        }
        return ['code' => 1, 'text' => '保存失败'];
    }
    
    /**
     * @param Request $request
     * @return mixed
     *  活体检测返回
     */
    public function faceverifyback(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $code = $request->input('code','');
        $key = 'face_verify_' . $code . '_' . $uid;
        $verify_uid = Redis::get($key);
        $user = User::select("id",'mobile')->where("id","=",$verify_uid)->first();
        if(!empty($user)) {
            $contents = Redis::get('face_video_base64_' . $code . '_' . $uid);;
            $user->alive_ok = 1;
            $disk = QiniuStorage::disk('qiniu');
            $filename = "video_" . date("YmdHis") . rand(111111,999999). ".mp4";
            $disk->put($filename,base64_decode($contents)); //上传文件
            $domain = config('filesystems.disks.qiniu.domain');
            $verify_alive_url = "http://$domain/$filename";
            $user->verify_alive_url = $verify_alive_url;
            $return['code'] = 0;
            $return['data'] = $uid;
            $user->save();
            return redirect("/html/verify_certification.html");
        }

    }

    /**
     * @param Request $request
     * @return mixed
     *  保存身份信息，防止页面刷新丢失
     */
    public function saveidcard(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $verify_name = trim($request->input('verify_name',''));
            $verify_idcard_no = trim($request->input('verify_idcard_no',''));
            $verify_idcard1_url = trim($request->input('verify_idcard1_url',''));
            $verify_idcard2_url = trim($request->input('verify_idcard2_url',''));

            $user = User::select("id",'mobile','idcard_ok')->where("id","=",$uid)->first();
            if(!empty($user)) {
                if(!empty($verify_name) && $user->idcard_ok == 0) {
                    $user->verify_name = $verify_name;
                }
                if(!empty($verify_idcard_no) && $user->idcard_ok == 0) {
                    $user->verify_idcard_no = $verify_idcard_no;
                }
                if(!empty($verify_idcard1_url) && strpos($verify_idcard1_url,$this->tpl_idcard1_url) === false) {
                    $user->verify_idcard1_url = $verify_idcard1_url;
                }
                if(!empty($verify_idcard2_url) && strpos($verify_idcard2_url,$this->tpl_idcard2_url) === false) {
                    $user->verify_idcard2_url = $verify_idcard2_url;
                }
                $return['code'] = 0;
                $return['text'] = '信息保存中，请稍后...';
                $user->save();
            }
        }
        return $return;

    }
    /**
     * @param Request $request
     * @return mixed
     *  更新身份信息
     */
    public function updateidcard(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $verify_name = trim($request->input('verify_name',''));
            $verify_idcard_no = trim($request->input('verify_idcard_no',''));
            $verify_idcard1_url = trim($request->input('verify_idcard1_url',''));
            $verify_idcard2_url = trim($request->input('verify_idcard2_url',''));
            if(empty($verify_name)) {
                $return['text'] = '请填写姓名';
                return $return;
            }
            if(empty($verify_idcard_no)) {
                $return['text'] = '请填写身份证号';
                return $return;
            }
            if(empty($verify_idcard1_url) || strpos($verify_idcard1_url,$this->tpl_idcard1_url) !== false) {
                $return['text'] = '请上传身份证正面照';
                return $return;
            }
            if(empty($verify_idcard2_url) || strpos($verify_idcard2_url,$this->tpl_idcard2_url) !== false) {
                $return['text'] = '请上传身份证反面照';
                return $return;
            }
            $user = User::select("id",'mobile')->where("id","=",$uid)->first();
            if(!empty($user)) {
                $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
                require_once($path);
                //echo "$path";exit();
                $is_photo = 'noPhoto';
                $trans_id = BaofooUtils::create_uuid();//商户订单号
                $trade_date = BaofooUtils::trade_date();//交易时间
                $arrayData=array(
                    "member_id" => $member_id,
                    "terminal_id" => $terminal_id,
                    "trans_id" => $trans_id,
                    "trade_date" => $trade_date,
                    "id_card" => $verify_idcard_no,
                    "id_holder" => $verify_name,
                    "is_photo" => $is_photo,
                    "industry_type" => "A1",////根据自己的业务类型传入参数
                );
                // *** 数据格式化***
                $data_content="";
                //==================转换数据类型=============================================
                if($data_type == "json"){
                    $data_content = str_replace("\\/", "/",json_encode($arrayData));//转JSON
                }
                //echo $data_content;
                // **** 先BASE64进行编码再RSA加密 ***
                $BFRsa = new BFRSA($pfxpath, $cerpath, $pfx_pwd,TRUE); //实例化加密类。
                $data_content = $BFRsa->encryptedByPrivateKey($data_content);
                Log::LogWirte("====加密串".$data_content);
                /**============== http 请求==================== **/
                //向服务器发送扣费请求
                $send_url = env('OTHER_API').'/api/realmsg';
                $params = [
                    'form_params' => [
                        'member_id' => $member_id,
                        'terminal_id' => $terminal_id,
                        'data_type' => $data_type,
                        'data_content' => $data_content,
                        'request_url' => $cardAuthUrl,
                        'sign' => env('SIGN'),
                        'uid' => $uid
                    ]
                ];
                try{
                    $result_data = $this->guzzle($send_url, $params);
                    $reslut = $result_data->getBody()->getContents();
                    $bind_decode = json_decode($reslut, true);
                    if($bind_decode['code']) return ['text' => $bind_decode['text']];
                }catch (\Exception $e){
                    @file_put_contents('../storage/logs/bindcard'.date('Ym').'.txt', $e->getMessage().date('Y-m-d H:i:s'), FILE_APPEND);
                }
                //TODO 开发环境用，生产环境关闭
                @file_put_contents('../storage/logs/updateidcard.log' , "\nRES：" . $reslut . "\n\n" ,FILE_APPEND);
                $arr = json_decode($reslut,true);
                if(isset($arr['success'])) {
                    if($arr['success'] == true) {
                        if(isset($arr['data']) && $arr['data']['code'] == 0) {
                            $return['code'] = 0;
                            $return['data'] = $arr['data'];
                            $user->verify_name = $verify_name;
                            $user->verify_idcard_no = $verify_idcard_no;
                            $user->verify_idcard1_url = $verify_idcard1_url;
                            $user->verify_idcard2_url = $verify_idcard2_url;
                            $user->idcard_ok = 1;

                            $return['code'] = 0;
                            $return['text'] = '验证通过';
                            $user->save();
                        } else {
                            $return['text'] =  $arr['data']['desc'];
                        }

                    } else {
                        $return['text'] = $arr['errorMsg'];
                    }
                }
            }
        }
        return $return;

    }

    /**
     * @param Request $request
     * @return mixed
     *  认证并更新银行卡信息
     */
    public function updatebankcard(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $verify_bankcard_no = trim($request->input('verify_bankcard_no',''));
            $mobile = trim($request->input('mobile',''));
            if(empty($verify_bankcard_no)) {
                $return['text'] = '请填写银行卡号';
                return $return;
            }
            if(empty($mobile)) {
                $return['text'] = '请填写手机号';
                return $return;
            }
            $user = User::select("id",'mobile')->where("id","=",$uid)->first();
            if(!empty($user)) {
                $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
                require_once($path);

                $trans_id = BaofooUtils::create_uuid();//商户订单号
                $trade_date = BaofooUtils::trade_date();//交易时间
                $card_type = '101';//$request->input('card_type','');
                $request_url = $bankCardAuthUrl;
                $arrayData=array(
                    "member_id"=>$member_id,
                    "terminal_id"=>$terminal_id,
                    "id_card"=>$user->verify_idcard_no,
                    "id_holder"=>$user->verify_name,
                    "acc_no"=>$verify_bankcard_no,
                    "mobile"=>$mobile,
                    "card_type"=>$card_type,
                    "trans_id"=>$trans_id,
                    "trade_date"=>$trade_date,

                    //"valid_date_year"=>'',
                    //"valid_date_month"=>'',
                    //"valid_no"=>'',
                    "verify_element"=>'1234',
                    "industry_type"=>"A1",//根据自己的行业类型传入
                    //"product_type"=>0,
                );
                // *** 数据格式化***
                $data_content="";
                //==================转换数据类型=============================================
                if($data_type == "json"){
                    $data_content = str_replace("\\/", "/",json_encode($arrayData));//转JSON
                }
                // **** 先BASE64进行编码再RSA加密 ***
                $BFRsa = new BFRSA($pfxpath, $cerpath, $pfx_pwd,TRUE); //实例化加密类。
                $data_content = $BFRsa->encryptedByPrivateKey($data_content);
                Log::LogWirte("====加密串".$data_content);
                /**============== http 请求==================== **/
                $PostArry = array(
                    "member_id" =>$member_id,
                    "terminal_id" => $terminal_id,
                    "data_type" => $data_type,
                    "data_content" => $data_content);
                @file_put_contents('../storage/logs/updatebankcard.log', $request_url . "\n" . json_encode($arrayData) . "\n" ,FILE_APPEND);
                $reslut = HttpClient::Post($PostArry, $request_url);  //发送请求到服务器，并输出返回结果。
                @file_put_contents('../storage/logs/updatebankcard.log' , "\nRES：" . $reslut . "\n\n" ,FILE_APPEND);
                $arr = json_decode($reslut,true);

                if(isset($arr['success'])) {
                    if($arr['success'] == true) {
                        if(isset($arr['data']) && $arr['data']['code'] == 0) {
                            $return['code'] = 0;
                            $return['data'] = $arr['data'];
                            $return['text'] = '银行卡认证成功';
                            $user->verify_bankcard_no = $verify_bankcard_no;
                            $user->verify_bankcard_mobile = $mobile;
                            $user->bankcard_ok = 1;
                            $user->save();
                        } else {
                            $return['text'] =  $arr['data']['desc'];
                        }

                    } else {
                        $return['text'] = $arr['errorMsg'];
                    }
                }

            }


        }
        return $return;

    }

    /**
     * @param Request $request
     * @return mixed
     *  芝麻分，支付宝关闭接口，暂时无法使用
     */
    public function sesamecredit(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $user = User::select("id",'mobile')->where("id","=",$uid)->first();
            if(!empty($user)) {
                require_once($_SERVER['DOCUMENT_ROOT'] . "/../alipay/aop/AopClient.php");
                require_once($_SERVER['DOCUMENT_ROOT'] . "/../alipay/aop/SignData.php");
                require_once($_SERVER['DOCUMENT_ROOT'] . "/../alipay/aop/request/ZhimaCreditScoreBriefGetRequest.php");
                require_once($_SERVER['DOCUMENT_ROOT'] . "/../alipay/lotusphp_runtime/Logger/Logger.php");

                $aop = new AopClient ();
                $aop->gatewayUrl = 'https://openapi.alipaydev.com/gateway.do';
                $aop->appId = '2016072900117671';
                $aop->rsaPrivateKey = 'MIIEpQIBAAKCAQEA/aXjr9AAC5ZpChsMcq69lhyF+O76HietM29vUQ5gMkDwzOvzzZQ+kmX9ix/1ixKgIo5duvL0uMKjMrgr6RaWbd0LO54VZVW8KCJALG/5dNR3OWmXGQBdDk1MQUe5RVP0gdX+EgddA6DcVTrDIUJeqOq/eb41cjW+o7VBj0V5FkzE86ar505BpW2M5s4g1xb42UNzZE+RtKvQIJVU5OU7iu0MBD5knfIlEAzgPXFySd+uE2H0gVmxLq/35y2OlxK8T36vSZ8zwF83AtNOTtwpV/U6WlhleOKb0tHULvnhfdCJY7DshYeK2i0euOTKfde7ydW1jOYn7DZ/ZKGMfKpOdQIDAQABAoIBAQC4KxgsEqnFwBtahBNAvdHYSbOY8OPYu1ROEW5Q+1ArjO2KzRPDxAy+vaEfwD/ID+kHzjkOQdQgxuo6LHFtl8H32VSLoBfG8T5iIaRY36DQDGjY3esg8xueA9AHYi2Kwg+5qggFTSVjOgxhMf52irsyiOgoXExwNcfLFBObFIV8AyW+MmvkKxHXI3Nl6si4ed01g3a3Z9i6Bs5gsbcTfLWWDJ1N/1+knYRZ8/5iIWGZJHAfZNMBoXTvbB4XtjcWlAwdh30/cc5EmV1iHwXcTZ+8YGKpxsuEubBUuKTzoU0W18qDDAYcJaX0STh4aLo5dUwqyofDrlo7+Gv67FmSQ1MNAoGBAP8FBmIVeYu7NolKDJafc11mwBYqv5XMl72tHh3Q5au8uCxYCI6/PxwnTiOxTtYG2plPBt5rx99Unb0NdoCzY8IXC3U7ah8Jph+59dhOxKy/Gz7PESkwFVj2Y65Gb3cdwYn2SF6zEfUlEyKEC3YlHGb08QLAZ2NnexM6oYgblJ/3AoGBAP6fg7yufErzoMjNoYVhJDbSFR59vPr3PGcRZV21r3M2gSnWAg/M18CffcBksQFxcT3TsEumIQR3UYbBcIUpZRN8jkL/RclxMMKm0mksTPvTN4AQoEU2TgWpwJMQYIjxV4xoOYiFpEwmLfedMgSqKefGuXaG+ebrveymKkdNHYHzAoGAMC1l2E/QR4qVsfgQSsBSzhlkPovS59zf6dBzuRRG31vmu1HiQ/1zUcFHLM0JZLukvoPEe26HMvTMW/PYKFY7iWZLHtmbocNz49iAzl2LIEt2PTZnOo2/6q+Zg0oBMtKnRoYFhAZ2ZQadB89ETwyRwg2SHn/0yD27bZWNAKadPF8CgYEAny8CoRdExWcCggdsj4JnrY4xfdqGJzAiJx2NDcTkZ1cP8SPGLjKWP+p2J63Lq2dMsKaDdQfrZGtkIKcWvWlfs4sPNXt6GbIWFdtNeEsl5dnqvLmoORz2MjwqFMcMUxDu9uzB60QBr0m/OyqfdqMbh7eJgzxnR6LiHezUSbdAV1kCgYEA00buz24mxyaPCiP77yyopi8NUPThNLpOsYa0YLERPZEp+V0keAskrccP76dr6Z5Wfw+xyz2XYUPFkg0I5NLjGMkVwsETo+ZuMSkBopg+xJSS7A9hiorI3E8jWEvrtrsedmh9mvH5hWdV4caD1MCgqre0MKXDWtbgNorXvU1BDjQ=';
                $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0a0jgC6TDXNvQtANowqOk26LQtsv6VQwBpI9ChaqIYMQ7Y3tDWTNu4WlFHgIiVTD2WAWWQ5Z/tkY8hzTFIQyTVVk9iX2g1xc4YCWDOacp3Aj1rHOHfcxb3nDuyDofNfdCUv2FUtRDeldLiT/LcXHr1+Vpk0rb3tMQGSW+q5FaDQZGKapLN7IzJYqiljv/MykvnXKCNUqHyvFxD4Zip3gDwPjgX3bJ78jlnDEdssrM6z0G2VJmfz8HqISrAk4KjGsfS2B7HhPMse31CiuWAnvk79Xs2HIBlKMnG41no1NHdg+xXOutJKsoad9NtEFRz6z/+/r3s/79oG5WRTRQnGnYQIDAQAB';
                $aop->apiVersion = '1.0';
                $aop->signType = 'RSA2';
                $aop->postCharset='UTF-8';
                $aop->format='json';
                $request = new ZhimaCreditScoreBriefGetRequest();
                $request->setBizContent("{" .
                    "\"transaction_id\":\"20151210093658804000000046515812\"," .
                    "\"product_code\":\"w1010100000000002733\"," .
                    "\"cert_type\":\"IDENTITY_CARD\"," .
                    "\"cert_no\":\"064345193210065222\"," .
                    "\"name\":\"沙箱环境\"," .
                    "\"admittance_score\":950," .
                    "\"linked_merchant_id\":\"2088102168999915\"" .
                    "  }");

                $result = $aop->execute($request);
                $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;
                if(!empty($resultCode)&&$resultCode == 10000){
                    $user->sesamecredit_ok = 1;
                    $user->save();
                    $return['code'] = 0;
                    $return['text'] = '芝麻信用认证成功';
                } else {
                    $return['text'] = '认证失败';
                }
            }
        }
        return $return;

    }

    /**
     * @param Request $request
     * @return mixed
     *  更新紧急联系人
     */
    public function updateemergencycontact(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $emergency_contact1_type = trim($request->input('emergency_contact1_type',''));
            $emergency_contact1_name = trim($request->input('emergency_contact1_name',''));
            $emergency_contact1_mobile = trim($request->input('emergency_contact1_mobile',''));
            $emergency_contact2_type = trim($request->input('emergency_contact2_type',''));
            $emergency_contact2_name = trim($request->input('emergency_contact2_name',''));
            $emergency_contact2_mobile = trim($request->input('emergency_contact2_mobile',''));

            if(empty($emergency_contact1_type)) {
                $return['text'] = '请选择联系人类型';
                return $return;
            }
            if(empty($emergency_contact1_name)) {
                $return['text'] = '请填写联系人姓名';
                return $return;
            }
            if(empty($emergency_contact1_mobile)) {
                $return['text'] = '请填写联系人手机号';
                return $return;
            }

            $user = User::select("id",'mobile')->where("id","=",$uid)->first();
            if(!empty($user)) {
                $user->emergency_contact1_type = $emergency_contact1_type;
                $user->emergency_contact1_name = $emergency_contact1_name;
                $user->emergency_contact1_mobile = $emergency_contact1_mobile;
                $user->emergency_contact2_type = $emergency_contact2_type;
                $user->emergency_contact2_name = $emergency_contact2_name;
                $user->emergency_contact2_mobile = $emergency_contact2_mobile;
                $user->emergency_contact_ok = 1;
                $user->save();
                $return['code'] = 0;
                $return['text'] = '添加成功';
            }

        }
        return $return;

    }

    /**
     * @param Request $request
     * @return mixed
     *  更新单位信息
     */
    public function updatecompany(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $company_name = trim($request->input('company_name',''));
            $company_tel = trim($request->input('company_tel',''));
            $company_address = trim($request->input('company_address',''));


            if(empty($company_name)) {
                $return['text'] = '请输入单位名称';
                return $return;
            }
            if(empty($company_tel)) {
                $return['text'] = '请输入单位电话';
                return $return;
            }
            if(empty($company_address)) {
                $return['text'] = '请输入单位地址';
                return $return;
            }


            $user = User::select("id",'mobile')->where("id","=",$uid)->first();
            if(!empty($user)) {
                $user->company_name = $company_name;
                $user->company_tel = $company_tel;
                $user->company_address = $company_address;
                $user->company_ok = 1;
                $user->save();
                $return['code'] = 0;
                $return['text'] = '添加成功';
            }

        }
        return $return;

    }

    /**
     * @param Request $request
     * @return mixed
     *  更新用户信息
     */
    public function updateuserinfo(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $emergency_contact1_type = trim($request->input('emergency_contact1_type',''));
            $emergency_contact1_name = trim($request->input('emergency_contact1_name',''));
            $emergency_contact1_mobile = trim($request->input('emergency_contact1_mobile',''));
            $emergency_contact2_type = trim($request->input('emergency_contact2_type',''));
            $emergency_contact2_name = trim($request->input('emergency_contact2_name',''));
            $emergency_contact2_mobile = trim($request->input('emergency_contact2_mobile',''));

            $company_name = trim($request->input('company_name',''));
            $company_tel = trim($request->input('company_tel',''));
            $company_address = trim($request->input('company_address',''));
            $company_city = trim($request->input('company_city',''));

            $reside_city = trim($request->input('reside_city',''));
            $reside_address = trim($request->input('reside_address',''));

            if(empty($emergency_contact1_type)) {
                $return['text'] = '请选择联系人类型';
                return $return;
            }
            if(empty($emergency_contact1_name)) {
                $return['text'] = '请填写联系人姓名';
                return $return;
            }
            if(empty($emergency_contact1_mobile)) {
                $return['text'] = '请填写联系人手机号';
                return $return;
            }
            
			$company_name = "这是默认公司，请忽略";
			$company_tel = "057112345678";
			$company_address = "浙江省杭州市这是默认地址请忽略";
			$company_city = "陕西省 汉中市 汉台区";    
			
            if(empty($company_name)) {
                $return['text'] = '请输入单位名称';
                return $return;
            }
            if(empty($company_tel)) {
                $return['text'] = '请输入单位电话';
                return $return;
            }
            if(empty($company_address)) {
                $return['text'] = '请输入单位地址';
                return $return;
            }
            if(empty($company_city)) {
                $return['text'] = '请输入单位城市';     
                return $return;    
            }
			
            if(empty($reside_city)) {
                $return['text'] = '请选择现居住';
                return $return;
            }
            if(empty($reside_address)) {
                $return['text'] = '请输入现居住详细地址';
                return $return;
            }
            $user = User::withoutGlobalScopes()->select("id")->where("id","=",$uid)->first();
            if(!empty($user)) {
                $user->emergency_contact1_type = $emergency_contact1_type;
                $user->emergency_contact1_name = $emergency_contact1_name;
                $user->emergency_contact1_mobile = $emergency_contact1_mobile;
                $user->emergency_contact2_type = $emergency_contact2_type;
                $user->emergency_contact2_name = $emergency_contact2_name;
                $user->emergency_contact2_mobile = $emergency_contact2_mobile;
                $user->emergency_contact_ok = 1;

                $user->company_name = $company_name;
                $user->company_tel = $company_tel;
                $user->company_address = $company_address;
                $user->company_city = $company_city;
                $user->reside_city = $reside_city;
                $user->reside_address = $reside_address;
                $user->company_ok = 1;
                $user->verify_info_date = date('Y-m-d H:i:s');

                $user->save();
                $return['code'] = 0;
                $return['text'] = '更新成功';
            }

        }
        return $return;

    }

    /**
     * @param Request $request
     * @return mixed
     *  更新用户信通讯录
     */
    public function updateContacts(Request $request)
    {
        try{
            $return['code'] = -1;
            $return['text'] = '';
            $mobile = session("mobile");
            $phone_contacts = $request->input('phone_contacts','');
            $contacts_arr = json_decode($phone_contacts,true);

            if(!empty($mobile)) {
                if(empty($contacts_arr) || !is_array($contacts_arr)) {
                    $return['text'] = '联系人不能为空';
                    return $return;
                }

                foreach ($contacts_arr as $key => $val) {
                    $phone = $val['phone'] ?? '无号码';
                    $name = $val['name'] ?? '无名';
                    $contacts[$phone] = $name;
                }

                User::withoutGlobalScopes()->where("mobile","=",$mobile)->update(['phone_contacts' => json_encode($contacts), 'phone_contacts_ok' => 1]);

                $return['code'] = 200;
                $return['text'] = '更新成功';
            }
        }catch (\Exception $ex){
            file_put_contents('../storage/logs/updateContacts.log', $ex->getMessage());
        }

         return $return;
    }
    /**
     * @param Request $request
     * @return mixed
     *  更新用户短信
     */
    public function updateMessages(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $mobile = session("mobile");
        $logined = intval(session("logined"));
        $datetime = date("Y-m-d H:i:s");
        $phone_messages = $request->input('phone_messages','');
        $search = array(" ","　","\n","\r","\t");
        $replace = array("","","","","");
        $phone_messages = str_replace($search, $replace, $phone_messages);
        @file_put_contents('../storage/logs/updateMessages_'.date("Ymd").'.log', $datetime . "\n" . $phone_messages  . "\n\n" ,FILE_APPEND);
        $messages_arr = json_decode($phone_messages,true);

        if(!empty($mobile)) {
            if(!is_array($messages_arr)) {
                $return['text'] = '短信不能为空';
                return $return;
            }

            foreach ($messages_arr as $key => $val) {
                $key = "{$val['phone']}-{$val['date']}";
                $messages[$key] = array(
                    'phone'    =>      $val['phone'],
                    'name'    =>      $val['name'],
                    'date'    =>      $val['date'],
                    'text'    =>      $val['text'],
                );
            }

            User::withoutGlobalScopes()->where("mobile", $mobile)->update(['phone_messages' => json_encode($messages)]);

            $return['code'] = 200;
            $return['text'] = '更新成功';
            return $return;

        }

        return $return;
    }
    /**
     * @param Request $request
     * @return mixed
     *  更新用户手机位置
     */
    public function updateLocation(Request $request)
    {
        $mobile =session("mobile");
        if($mobile) {
            $lon = trim($request->input('lon',''));
            $lat = trim($request->input('lat',''));
            if(empty($lon) || empty($lat)) {
                $return['text'] = '经纬度不能为空';
                return $return;
            }

            User::withoutGlobalScopes()->where("mobile","=",$mobile)->update(['phone_location' => "$lon,$lat"]);
        }
        $return['code'] = 200;
        $return['text'] = '更新成功';
        return $return;
    }
    /**
     * @param Request $request
     * @return mixed
     *  更新手机应用程序名称
     */
    public function updateAppNames(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '更新失败';
        $mobile = session("mobile");
        if($mobile) {
            $appnamesjson = trim($request->input('appnames',''));
			$arr = json_decode($appnamesjson,true);
			if(!empty($arr)) {
				$appnames = array();
				$packagenames = array();
				foreach($arr as $key => $val) {
					$packagename = $val['packagename'];
					if(!in_array($packagename,$packagenames)) {
						$appnames[] = $val;
					}
					$packagenames[] = $packagename;
				}

                User::withoutGlobalScopes()->where("mobile","=",$mobile)->update(['phone_appnames' => json_encode($appnames)]);
			}
            $return['code'] = 200;
            $return['text'] = '更新成功';
        }
        return $return;
    }
    /**
     * @param Request $request
     * @return mixed
     *  跳转到新颜获取“全知”数据
     */
    public function gotoxinyan(Request $request)
    {
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
            require_once($path);

            $apiName = trim($request->input('apiname',''));
            $apiUser = $member_id;
            $timeMark = date("YmdHis");
            $taskId = $uid . time() . rand(111111,999999);//商户订单号
            $jumpUrl = urlencode(url("html/verify.html"));
            $apiKey = '035vE48L47o51210';
            //第三方服务器存档
            $send_url = env('OTHER_API').'/api/getTaskidUrl';
            $params = [
                'form_params' => [
                    'taskid' => $taskId,
                    'sign' => env('SIGN'),
                    'apiname' => $apiName,
                    'uid' => $uid
                ]
            ];

            try{
                $response = $this->guzzle($send_url, $params);
                $reslut = $response->getBody()->getContents();
                $bind_decode = json_decode($reslut, true);
                if($bind_decode['code']) return ['text' => $bind_decode['text']];
            }catch (\Exception $e){
                file_put_contents('./bindcard.txt', $e->getMessage().date('Y-m-d H:i:s'), FILE_APPEND);
            }

            $str = $apiUser.$timeMark.$apiName.$taskId.$apiKey;
            $apiEnc = md5($str);
            //echo "$apiUser,$timeMark,$apiName,$taskId,$apiKey<br/>";
            $datetime = date("Y-m-d H:i:s");
            $url = "https://qz.xinyan.com/h5/{$apiUser}/{$apiEnc}/{$timeMark}/{$apiName}/{$taskId}?jumpUrl={$jumpUrl}";
            //exit("$url");
            @file_put_contents('../storage/logs/gotoxinyan_'.date("Ym").'.log', $datetime . "\n" . "$url" . "\n\n" ,FILE_APPEND);
            $userQzxinyanQuery = new UserQzxinyanQuery();
            $userQzxinyanQuery->user_id = $uid;
            $userQzxinyanQuery->apiname = $apiName;
            $userQzxinyanQuery->taskid = $taskId;
            $userQzxinyanQuery->url = $url;
            $userQzxinyanQuery->data = '';
            $userQzxinyanQuery->datareport = '';
            $userQzxinyanQuery->created_at = $datetime;
            $userQzxinyanQuery->save();
            return redirect($url);
        }
        return "跳转失败";

    }
    //新颜回调通知-数据
    public function notify(Request $request)
    {
        $body = $request->all();
        $return['code'] = -1;
        $return['text'] = '';
        $datetime = date("Y-m-d H:i:s");
        @file_put_contents('../storage/logs/notify.log', $datetime . "\n" . json_encode($_GET) . "\n" .json_encode($body) . "\n" ,FILE_APPEND);

        $arr = $body;
        if(!empty($arr)) {
            $taskId = $arr['taskId'];
            $token = $arr['token'];
            $userQzxinyanQuery = UserQzxinyanQuery::where("taskid",'=',$taskId)->first();
            if(!empty($userQzxinyanQuery)) {
                if(!empty($token)) {
                    $user_id = $userQzxinyanQuery->user_id;
                    $apiname = $userQzxinyanQuery->apiname;
                    $userQzxinyanQuery->token = $token;
                    if($apiname == 'carrier') {
                        $update = array("carrier_ok" => -1);
                        User::where("id","=",$user_id)->update($update);
                    }
                    if($apiname == 'taobaoweb') {
                        $update = array("taobaoweb_ok" => -1);
                        User::where("id","=",$user_id)->update($update);
                    }
                    $userQzxinyanQuery->save();
                }

                $return['code'] = 0;
                $return['text'] = 'OK';
            }
        }
        return $return;
    }
    //新颜回调通知-报表
    public function reportnotify(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        $body = file_get_contents('php://input');
        echo "ok";
        $datetime = date("Y-m-d H:i:s");
        @file_put_contents('../storage/logs/reportnotify.log', $datetime . "\n" . json_encode($_GET) . "\n" .$body . "\n" ,FILE_APPEND);

        return $return;

    }

    //绑卡发送短信-富友
    public function bindCardSendMsg(Request $request) {

        $return['code'] = -1;
        $return['text'] = '失败';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        $user = User::select("id",'mobile','verify_name','verify_idcard_no','verify_bankcard_no')->where("id","=",$uid)->first();
        if(!empty($user) && $logined == 1) {
            $verify_bankcard_no = trim($request->input('verify_bankcard_no',''));
            $verify_bankcard_mobile = trim($request->input('verify_bankcard_mobile',''));

            $verify_name = $user->verify_name;
            $verify_idcard_no = $user->verify_idcard_no;
            $auto = 1;
            if($auto == 1) {
                if(!empty($verify_name) && !empty($verify_idcard_no) && !empty($verify_bankcard_no) && !empty($verify_bankcard_mobile)) {
                    #调用接口
                    $VERSION = "1.00";
                    $merdt = date("Ymd");
                    $CARDNO = $verify_bankcard_no;
                    $IDCARD = $verify_idcard_no;
                    $MCHNTSSN = date("YmdHis") . rand(11111111,99999999);
                    $ACCOUNT = $verify_name;
                    $IDTYPE = "0";
                    $MOBILENO = $verify_bankcard_mobile;
                    $MCHNTCD = $this->fuiouMchntcd;
                    $mchntkey = $this->fuiouMchntKey;
                    $USERID = $uid;
                    $str = "$VERSION|$MCHNTSSN|$MCHNTCD|$USERID|$ACCOUNT|$CARDNO|$IDTYPE|$IDCARD|$MOBILENO|$mchntkey";
                    $SIGN = md5($str);
                    $SIGN = strtoupper($SIGN);
                    $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <REQUEST> <VERSION>$VERSION</VERSION> <MCHNTCD>$MCHNTCD</MCHNTCD> <USERID>$USERID</USERID> <TRADEDATE>$merdt</TRADEDATE> <MCHNTSSN>$MCHNTSSN</MCHNTSSN> <ACCOUNT>$ACCOUNT</ACCOUNT> <CARDNO>$CARDNO</CARDNO> <IDTYPE>$IDTYPE</IDTYPE> <IDCARD>$IDCARD</IDCARD> <MOBILENO>$MOBILENO</MOBILENO> <CVN></CVN> <SIGN>$SIGN</SIGN> </REQUEST>";

                    $size = mcrypt_get_block_size('des','ecb');
                    $input = self::pkcs5_pad($xml, $size);
                    $td = mcrypt_module_open('des', '', 'ecb', '');
                    $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
                    @mcrypt_generic_init($td, $mchntkey, $iv);
                    $data = mcrypt_generic($td, $input);
                    mcrypt_generic_deinit($td);
                    mcrypt_module_close($td);
                    $data = base64_encode($data);

                    $list=array("MCHNTCD" => $MCHNTCD,"APIFMS" => $data);
                    $url="https://mpay.fuioupay.com/newpropay/bindMsg.pay";
                    $query = http_build_query($list);
                    $options = array(
                        'http' => array(
                            'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                                "Content-Length: ".strlen($query)."\r\n".
                                "User-Agent:MyAgent/1.0\r\n",
                            'method'  => "POST",
                            'content' => $query,
                        ),
                    );
                    $yearMonth = date("Ym");
                    @file_put_contents('../storage/logs/transfer_bindSendMsg_' . $yearMonth . '.log', $url . "\nPOST:" . $str . "\n" ,FILE_APPEND);
                    $context = stream_context_create($options);
                    $result = file_get_contents($url, false, $context, -1, 40000);

                    $input = base64_decode($result);
                    $size = mcrypt_get_block_size('des','ecb');
                    $td = mcrypt_module_open('des', '', 'ecb', '');
                    $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
                    @mcrypt_generic_init($td, $mchntkey, $iv);
                    $data = mdecrypt_generic($td, $input);
                    mcrypt_generic_deinit($td);
                    mcrypt_module_close($td);
                    $datades = self::pkcs5_unpad($data, $size);


                    $postObj = simplexml_load_string($datades, 'SimpleXMLElement', LIBXML_NOCDATA);
                    $jsonStr = json_encode($postObj);
                    $jsonArray = json_decode($jsonStr,true);
                    @file_put_contents('../storage/logs/transfer_bindSendMsg_' . $yearMonth . '.log',  "\nRES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                    if(!empty($jsonArray) && $jsonArray['RESPONSECODE'] == '0000') {
                        @file_put_contents('../storage/logs/transfer_bindSendMsg_success_' . $yearMonth . '.log',  $url . "\nPOST:" . json_encode($options) . "\nRES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                        $session = [
                            'fuiou_MCHNTSSN'  =>  $jsonArray['MCHNTSSN'],
                        ];
                        session($session);
                        $return['code'] = 0;
                        $return['text'] = '已发送';
                    }  else {
                        $return['text'] = $jsonArray['RESPONSEMSG'];
                    }
                }
            }
        }
        return $return;

    }
    //绑卡-富友
    public function v1_bindCard(Request $request) {

        $return['code'] = -1;
        $return['text'] = '失败';
        $vcode = $request->input('vcode','');
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        $user = User::select(['id', 'channel_id', 'mobile','name','avatar','score','verify_name','verify_idcard_no','verify_bankcard_no','verify_bankcard_mobile','changjie_protocol_no','verify_idcard1_url','verify_idcard2_url','verify_alive_url','idcard_ok','alive_ok','bankcard_ok','sesamecredit_ok','emergency_contact_ok','company_ok','carrier_ok','taobaoweb_ok','emergency_contact1_type','emergency_contact1_name','emergency_contact1_mobile','emergency_contact2_type','emergency_contact2_name','emergency_contact2_mobile','company_name','company_address','company_tel','state','convert','created_at','updated_at'])->where("id","=",$uid)->first();
        $fuiou_MCHNTSSN = trim(session("fuiou_MCHNTSSN"));
        if(empty($vcode)) {
            $return['text'] = '请输入验证码';
            return $return;
        }
        if(!empty($user) && $logined == 1 && !empty($fuiou_MCHNTSSN) && !empty($vcode)) {
            $verify_bankcard_no = trim($request->input('verify_bankcard_no',''));
            $verify_bankcard_mobile = trim($request->input('verify_bankcard_mobile',''));
            $vcode = trim($request->input('vcode',''));
            $verify_name = $user->verify_name;
            $verify_idcard_no = $user->verify_idcard_no;
            $auto = 1;
            if($auto == 1) {
                if(!empty($verify_name) && !empty($verify_idcard_no) && !empty($verify_bankcard_no) && !empty($verify_bankcard_mobile)) {
                    #调用接口
                    $VERSION = "1.00";
                    $merdt = date("Ymd");
                    $CARDNO = $verify_bankcard_no;
                    $IDCARD = $verify_idcard_no;
                    $MCHNTSSN = $fuiou_MCHNTSSN;
                    $ACCOUNT = $verify_name;
                    $IDTYPE = "0";
                    $MOBILENO = $verify_bankcard_mobile;
                    $MCHNTCD = $this->fuiouMchntcd;
                    $mchntkey =  $this->fuiouMchntKey;
                    $USERID = "1";
                    $MSGCODE = $vcode;
                    $str = "$VERSION|$MCHNTSSN|$MCHNTCD|$USERID|$ACCOUNT|$CARDNO|$IDTYPE|$IDCARD|$MOBILENO|$MSGCODE|$mchntkey";
                    $SIGN = md5($str);
                    $SIGN = strtoupper($SIGN);
                    $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <REQUEST> <VERSION>$VERSION</VERSION> <MCHNTCD>$MCHNTCD</MCHNTCD> <USERID>$USERID</USERID> <TRADEDATE>$merdt</TRADEDATE> <MCHNTSSN>$MCHNTSSN</MCHNTSSN> <ACCOUNT>$ACCOUNT</ACCOUNT> <CARDNO>$CARDNO</CARDNO> <IDTYPE>$IDTYPE</IDTYPE> <IDCARD>$IDCARD</IDCARD> <MOBILENO>$MOBILENO</MOBILENO> <CVN></CVN> <MSGCODE>$MSGCODE</MSGCODE> <SIGN>$SIGN</SIGN> </REQUEST>";

                    $size = mcrypt_get_block_size('des','ecb');
                    $input = self::pkcs5_pad($xml, $size);
                    $td = mcrypt_module_open('des', '', 'ecb', '');
                    $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
                    @mcrypt_generic_init($td, $mchntkey, $iv);
                    $data = mcrypt_generic($td, $input);
                    mcrypt_generic_deinit($td);
                    mcrypt_module_close($td);
                    $data = base64_encode($data);

                    $list=array("MCHNTCD" => $MCHNTCD,"APIFMS" => $data);
                    $url="https://mpay.fuioupay.com/newpropay/bindCommit.pay";
                    $query = http_build_query($list);
                    $options = array(
                        'http' => array(
                            'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                                "Content-Length: ".strlen($query)."\r\n".
                                "User-Agent:MyAgent/1.0\r\n",
                            'method'  => "POST",
                            'content' => $query,
                        ),
                    );
                    $yearMonth = date("Ym");
                    $context = stream_context_create($options);
                    $result = file_get_contents($url, false, $context, -1, 40000);

                    $input = base64_decode($result);
                    $size = mcrypt_get_block_size('des','ecb');
                    $td = mcrypt_module_open('des', '', 'ecb', '');
                    $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
                    @mcrypt_generic_init($td, $mchntkey, $iv);
                    $data = mdecrypt_generic($td, $input);
                    mcrypt_generic_deinit($td);
                    mcrypt_module_close($td);
                    $datades = self::pkcs5_unpad($data, $size);

                    $postObj = simplexml_load_string($datades, 'SimpleXMLElement', LIBXML_NOCDATA);
                    $jsonStr = json_encode($postObj);
                    $jsonArray = json_decode($jsonStr,true);
                    @file_put_contents('../storage/logs/transfer_bind_' . $yearMonth . '.log',  "\nXML:" . $xml  . "\nRES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                    if(!empty($jsonArray) && $jsonArray['RESPONSECODE'] == '0000') {
                        @file_put_contents('../storage/logs/transfer_bind_success_' . $yearMonth . '.log',  $url . "\nPOST:" . json_encode($options) . "\nRES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                        $return['code'] = 0;
                        $return['text'] = '绑定成功';
                        $user->changjie_protocol_no = $jsonArray['PROTOCOLNO'];
                        $user->verify_bankcard_no = $verify_bankcard_no;
                        $user->verify_bankcard_mobile = $verify_bankcard_mobile;
                        $user->bankcard_ok = 1;
                        $user->save();
                    }  else {
                        //$return['text'] = json_encode($jsonArray);
                        $return['text'] = $jsonArray['RESPONSEMSG'];
                    }
                } else {
                    $return['text'] = "失败2";
                }
            }
        }
        return $return;
    }
    //绑卡查询接口 测试时用
    public function query_bind_card(){
        $postData = array();
        $user_id = '1656';
        $begin = '621700';
        $end = '1678';
        // 基本参数
        $postData['Service'] = 'nmg_api_auth_info_qry';
        $postData['Version'] = '1.0';
        $postData['PartnerId'] = $this->changjieMchntcd;;//商户号
        $postData['InputCharset'] = 'UTF-8';
        $postData['TradeDate'] = date('Ymd').'';
        $postData['TradeTime'] = date('His').'';
        $postData['Memo'] = '备注';

        // 4.4.2.10	绑卡查询接口 业务参数
        $postData['TrxId'] = time(); //外部流水号
        $postData['MerUserId'] =   (string)$user_id; //用户标识
        $postData['BkAcctTp'] =   '01'; //卡类型（00 –银行贷记账户;01 –银行借记账户;）
        $postData['CardBegin'] = $begin; //卡号前6位
        $postData['CardEnd'] = $end;//卡号后4位
        $postData['Extension'] = '';//扩展字段
        $postData['Sign'] = $this->rsaSign($postData);
        $postData['SignType'] = 'RSA'; //签名类型

        $query = http_build_query($postData);
        $url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url
        $jsonstr = $this->httpGet_a($url);
        $json = json_decode($jsonstr, true);
        echo '<pre>';
        var_dump($json);
    }
    //畅捷的解绑接口 测试时使用
    public function unbindCard($user_data){
        $user_id = $user_data['id'];
        $begin = $user_data['beforecard'];
        $end = $user_data['aftercard'];
        $postData = array();
        // 基本参数
        $postData['Service'] = 'nmg_api_auth_unbind';
        $postData['Version'] = '1.0';
        $postData['PartnerId'] = $this->changjieMchntcd;//商户号
        $postData['InputCharset'] = 'UTF-8';
        $postData['TradeDate'] = date('Ymd').'';
        $postData['TradeTime'] = date('His').'';
        $postData['Memo'] = '备注';

        // 4.4.2.4	鉴权解绑接口（API） 业务参数
        $postData['TrxId'] = time().substr(microtime(), 2, 5);; //外部流水号
        $postData['MerchantNo'] =   $this->changjieMchntcd; //商户编号
        $postData['MerUserId'] =   (string)$user_id; //用户标识
        $postData['UnbindType'] =   '1'; //解绑模式，0为物理删除，1为逻辑删除
        $postData['CardBegin'] = $begin; //卡号前6位
        $postData['CardEnd'] = $end;//卡号后4位
        $postData['Extension'] = '';//扩展字段
        $postData['Sign'] = $this->rsaSign($postData);
        $postData['SignType'] = 'RSA'; //签名类型
        $query = http_build_query($postData);
        $url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url
        $jsonstr = $this->httpGet_a($url);
        $json = json_decode($jsonstr, true);
        file_put_contents('../storage/logs/unbind_card_'.date('Ym').'.log', 'RES='.json_encode($json).'POST='.json_encode($postData).'||date='.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
        return $json;
        echo '<pre>';
        var_dump($json);
    }
    //畅捷和合利宝绑卡请求接口  合力宝没有回调
    public function bindCard(Request $request){
        $return['code'] = -1;
        $return['text'] = '失败';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        //阻止按钮的过分提交
        $isHasSub = CommonController::comRedis('bind_card_'.$uid, 5);
        if(!$isHasSub){
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        $user = User::select(['id', 'channel_id', 'mobile','name','avatar','score','verify_name','verify_idcard_no','verify_bankcard_no','verify_bankcard_mobile','changjie_protocol_no','verify_idcard1_url','verify_idcard2_url','verify_alive_url','idcard_ok','alive_ok','bankcard_ok','sesamecredit_ok','emergency_contact_ok','company_ok','carrier_ok','taobaoweb_ok','emergency_contact1_type','emergency_contact1_name','emergency_contact1_mobile','emergency_contact2_type','emergency_contact2_name','emergency_contact2_mobile','company_name','company_address','company_tel','state','convert','created_at','updated_at'])->where("id","=",$uid)->first();
        if(!empty($user) && $logined == 1) {
            $verify_bankcard_no = trim($request->input('verify_bankcard_no',''));
            $verify_bankcard_mobile = trim($request->input('verify_bankcard_mobile',''));
            $verify_name = trim($request->input('verify_name',''));
            $verify_idcard_no = trim($request->input('verify_idcard_no',''));
            $user_verify_name = $user->verify_name;
            $user_verify_idcard_no = $user->verify_idcard_no;
            if($verify_name != $user_verify_name){
                $return['text'] = '用户名与注册用户不一致';
                return $return;
            }
            if($verify_idcard_no != $user_verify_idcard_no){
                $return['text'] = '身份证号与注册用户不一致';
                return $return;
            }
            if(!empty($verify_name) && !empty($verify_idcard_no) && !empty($verify_bankcard_no) && !empty($verify_bankcard_mobile)) {
                $peopleArr['verify_bankcard_mobile'] = $verify_bankcard_mobile;
                $peopleArr['verify_bankcard_no'] = $verify_bankcard_no;
                $peopleArr['verify_idcard_no'] = $verify_idcard_no;
                $peopleArr['user_verify_name'] = $user_verify_name;
                $peopleArr['uid'] = $uid;

                //选择调用的支付接口,从文件缓存里取数据
                $product_base = $this->product_config();
                $customer = $product_base['bankcard'];

                if($customer == '1'){
                    //调用宝和的绑卡接口
                    $baohe = (new BaohePayController())->bindCard($peopleArr);
                    if($baohe['code'] == 0){
                        if($baohe['data']['rt2_retCode'] == '0000' && $baohe['data']['smsStatus'] == 'SUCCESS'){
                            //更新用户的商户号，用于切换通道的时候做条件
                            $user->helibao_protocol_no = env('BAOLIHE_MERCHANNO');
                            $user->save();
                            return ['code' => 0, 'text' => '验证码发送成功', 'OriAuthTrxId' => $baohe['data']['rt6_orderId']];
                        }else{
                            return ['code' => 1, 'text' => '验证码发送失败'];
                        }
                    }else{
                        return $baohe;//请求失败
                    }
                }elseif($customer == '2'){
                    $postData = array();
                    // 基本参数
                    $postData['Service'] = 'nmg_biz_api_auth_req';
                    $postData['Version'] = '1.0';
                    $postData['PartnerId'] = $this->changjieMchntcd;//商户号
                    $postData['InputCharset'] = 'UTF-8';
                    $postData['TradeDate'] = date('Ymd').'';
                    $postData['TradeTime'] = date('His').'';
                    $postData['Memo'] = '备注';

                    // 4.4.2.1. 鉴权绑卡请求（API） 业务参数
                    $postData['TrxId'] = time().substr(microtime(), 2, 5); //外部流水号
                    $postData['MerchantNo'] =   $this->changjieMchntcd; //商户编号，与支付请求接口中SellerId保持一致
                    $postData['ExpiredTime'] =   '90m'; //订单有效期，取值范围：1m～48h。单位为分，如1.5h，可转换为90m。用来标识本次鉴权订单有效时间，超过该期限则该笔订单作废
                    $postData['MerUserId'] =   (string)$uid; //用户标识（测试时需要换一个meruserid）
                    $postData['BkAcctTp'] =   '01'; //卡类型（00 –银行贷记账户;01 –银行借记账户;）
                    $postData['BkAcctNo'] =   $this->rsaEncrypt($verify_bankcard_no); //卡号
                    $postData['IDTp'] =   '01'; //证件类型，01：身份证
                    $postData['IDNo'] =   $this->rsaEncrypt($verify_idcard_no); //证件号
                    $postData['CstmrNm'] =   $this->rsaEncrypt($verify_name); //持卡人姓名
                    $postData['MobNo'] =   $this->rsaEncrypt($verify_bankcard_mobile); //银行预留手机号
                    $postData['CardCvn2'] =   $this->rsaEncrypt(''); //CVV2码，当卡类型为信用卡时必填
                    $postData['CardExprDt'] =   $this->rsaEncrypt(''); //有效期，当卡类型为信用卡时必填
                    $postData['SmsFlag'] =   '1'; //短信发送标识，0：不发送短信1：发送短信
                    $postData['NotifyUrl'] = env('SELF_HOST').'/api/user/bindcard/notify';//异步通知地址
                    $postData['Extension'] = '';//扩展字段
                    $postData['Sign'] = $this->rsaSign($postData);
                    $postData['SignType'] = 'RSA'; //签名类型
                    $query = http_build_query($postData);
                    $url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url
                    $jsonstr = $this->httpGet_a($url);
                    @file_put_contents('../storage/logs/cj_bind_card_'.date('Ymd').'.log', $jsonstr.'||postData='.json_encode($postData).'||date='.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
                    $json = json_decode($jsonstr, true);
                    if($json['Status'] == 'S' || $json['Status'] == 'P'){
                        $user->verify_bankcard_no = $verify_bankcard_no;
                        $user->verify_bankcard_mobile = $verify_bankcard_mobile;
                        $user->changjie_protocol_no = env('CHANGJIE_MERCHANNO');
                        $user->save();
                        return ['code' => 0, 'text' => '验证码已发送', 'OriAuthTrxId' => $json['TrxId']];
                    }elseif($json['Status'] == 'F' && $json['AppRetcode'] == 'QT300008'){
                        return ['code' => 1, 'text' => '此卡已绑定，请勿重复绑卡'];
                    }elseif($json['Status'] == 'F' && $json['AppRetcode'] == 'QT700001'){
                        return ['code' => 1, 'text' => '输入的银行卡号有误'];
                    }else{
                        return ['code' => 1, 'text' => '用户状态异常'];
                    }
                }
            }
        }
        return $return;
    }
    //畅捷绑卡的回调
    public function bindCardNotify(Request $request)
    {
        $receive['notify_id'] = trim($request->input('notify_id', ''));//交易订单号
        $receive['notify_type'] = trim($request->input('notify_type', ''));//交易订单号
        $receive['notify_time'] = trim($request->input('notify_time', ''));//交易订单号
        $receive['_input_charset'] = trim($request->input('_input_charset', ''));//扩展参数
        $receive['sign'] = trim($request->input('sign', ''));
        $receive['sign_type'] = trim($request->input('sign_type', ''));
        $receive['version'] = trim($request->input('version', ''));

        $receive['source_voucher_no'] = trim($request->input('source_voucher_no', ''));//订单支付中的一笔订单号
        $receive['auth_status'] = trim($request->input('auth_status', ''));//交易订单号
        $receive['bank_code'] = trim($request->input('bank_code', ''));//交易订单号
        $receive['bank_name'] = trim($request->input('bank_name', ''));//交易订单号
        $receive['mer_user_id'] = trim($request->input('mer_user_id', ''));//扩展参数
        $receive['card_begin'] = trim($request->input('card_begin', ''));//扩展参数
        $receive['card_end'] = trim($request->input('card_end', ''));//扩展参数
        $receive['ext'] = trim($request->input('ext', ''));//扩展参数

        $verify_sign = $this->rsaVerify($receive);
        if($verify_sign){

            $datetime = date("Y-m-d H:i:s");
            @file_put_contents('../storage/logs/bind_card_notify_'.date('Ym').'.log', $datetime . "||" . json_encode($receive).'||verifysing='.$verify_sign. PHP_EOL, FILE_APPEND);
            return 'success';
        }else{
            return ['code' => -1, 'text' => '非法访问'];
        }
    }
    //宝和解绑接口
    public function baoheUnbindCard($user_data){
        $baoheUnbind = new BaohePayController();
        $baoheUnbind->unbindCard($user_data);
        echo 'success';
    }
    //畅捷和宝和的绑卡确认接口
    public function defineBindCard(Request $request){
        $return['code'] = -1;
        $return['text'] = '失败';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        //阻止按钮的过分提交
        $isHasSub = CommonController::comRedis('define_bind_card_'.$uid, 5);
        if(!$isHasSub){
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        $user = User::select(['id', 'channel_id', 'mobile','name','avatar','score','verify_name','verify_idcard_no','verify_bankcard_no','verify_bankcard_mobile','changjie_protocol_no','verify_idcard1_url','verify_idcard2_url','verify_alive_url','idcard_ok','alive_ok','bankcard_ok','sesamecredit_ok','emergency_contact_ok','company_ok','carrier_ok','taobaoweb_ok','emergency_contact1_type','emergency_contact1_name','emergency_contact1_mobile','emergency_contact2_type','emergency_contact2_name','emergency_contact2_mobile','company_name','company_address','company_tel','state','convert','created_at','updated_at'])->where("id","=",$uid)->first();
        if(!empty($user) && $logined == 1) {
            //选择调用的支付接口,从文件缓存里取数据
            $product_base = $this->product_config();
            $customer = $product_base['bankcard'];
            if($customer != 3){
                $SmsCode = trim($request->input('SmsCode',''));
                $OriAuthTrxId = trim($request->input('OriAuthTrxId',''));
                if(empty($SmsCode)){
                    $return['text'] = '验证码不能为空';
                    return $return;
                }
                //生成数据
                $definedData['SmsCode'] = $SmsCode;
                $definedData['OriAuthTrxId'] = $OriAuthTrxId;
            }

            if($customer == '1'){
                //调用宝和的确定绑卡接口
                $baohe = (new BaohePayController())->definedBindCard($definedData);
                if($baohe['code'] == 0){
                    if($baohe['data']['rt7_bindStatus'] == 'SUCCESS' || $baohe['data']['rt7_bindStatus'] == 'DOING'){
                        //接通jcz
                        $send_url = env('OTHER_API').'/api/bindCard';
                        $params = [
                            'form_params' => [
                                'sign' => env('SIGN'),
                                'uid' => $uid,
                            ]
                        ];
                        try{
                            $res = $this->guzzle($send_url, $params);
                            $response = json_decode($res->getBody()->getContents(), true);
                            @file_put_contents('../storage/logs/baohe_define_bindcard_charge_'.date('Ym').'.log', date('Y-m-d H:i:s').'||post='.$params.'||res='.json_encode($response).'user_id='.$uid.PHP_EOL, FILE_APPEND);
                        }catch (\Exception $ex){
                            @file_put_contents('../storage/logs/baohe_defined_bind_card_exception_'.date('Ym').'.txt', $ex->getMessage().'||user_id='.$uid.'||date='.date('Y-m-d H:i:s'), FILE_APPEND);
                            return ['code' => 1, 'text' => '服务器异常，绑卡失败!'];
                        }
                        //写入绑卡后的表
                        $bind_card = BindCard::where('user_id', $baohe['data']['rt5_userId'])->first();
                        if(!count($bind_card)){
                            $bind_card = new BindCard();
                            $bind_card->user_id = $baohe['data']['rt5_userId'];
                        }
                        $bind_card->bind_id = $baohe['data']['rt10_bindId'];
                        $bind_card->order_id = $baohe['data']['rt6_orderId'];
                        $bind_card->save();

                        $transData = explode('_', $baohe['data']['rt6_orderId']);

                        $user->verify_bankcard_no = $transData[0];
                        $user->verify_bankcard_mobile = $transData[1];
                        $user->bankcard_ok = 1;
                        $user->save();
                        return ['code' => 0, 'text' => '绑卡成功'];
                    }else{
                        return ['code' => 1, 'text' => '绑卡失败'];
                    }
                }else{
                    return $baohe;//请求失败
                }
            }elseif($customer == '2'){
                //畅捷支付
                $postData = array();
                // 基本参数
                $postData['Service'] = 'nmg_api_auth_sms';
                $postData['Version'] = '1.0';
                $postData['PartnerId'] = $this->changjieMchntcd;//商户号
                $postData['InputCharset'] = 'UTF-8';
                $postData['TradeDate'] = date('Ymd').'';
                $postData['TradeTime'] = date('His').'';
                $postData['Memo'] = '备注';

                // 4.4.2.3. 鉴权绑卡确认接口（API） 业务参数
                $postData['TrxId'] = time().substr(microtime(), 2, 5); //外部流水号
                $postData['OriAuthTrxId'] =   $OriAuthTrxId; //填写需要退款的原始订单号
                $postData['SmsCode'] =   $SmsCode; //鉴权短信验证码
                $postData['Extension'] = '';//扩展字段
                $postData['Sign'] = $this->rsaSign($postData);
                $postData['SignType'] = 'RSA'; //签名类型

                $query = http_build_query($postData);
                $url = 'https://pay.chanpay.com/mag-unify/gateway/receiveOrder.do?'. $query; //该url为生产环境url

                $jsonstr = $this->httpGet_a($url);
                file_put_contents('../storage/logs/define_bind_card_'.date('Ym').'.txt', $jsonstr . '||user_id='.$uid.'||date=' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
                $json = json_decode($jsonstr, true);
                if($json['Status'] == 'S'){
                    //接通jcz
                    $send_url = env('OTHER_API').'/api/bindCard';
                    $params = [
                        'form_params' => [
                            'sign' => env('SIGN'),
                            'uid' => $uid,
                        ]
                    ];
                    try{
                        $res = $this->guzzle($send_url, $params);
                        $response = json_decode($res->getBody()->getContents(), true);
                        @file_put_contents('../storage/logs/define_bindcard_charge_'.date('Ym').'.log', date('Y-m-d H:i:s').'||post='.$params.'||res='.json_encode($response).'user_id='.$uid.PHP_EOL, FILE_APPEND);
                    }catch (\Exception $ex){
                        @file_put_contents('../storage/logs/defined_bind_card_exception_'.date('Ym').'.txt', $ex->getMessage().'||user_id='.$uid.'||date='.date('Y-m-d H:i:s'), FILE_APPEND);
                        return ['code' => 1, 'text' => '服务器异常，绑卡失败!'];
                    }

                    $user->bankcard_ok = 1;
                    $user->save();
                    return ['code' => 0, 'text' => '绑卡成功'];
                }elseif($json['Status'] == 'F' && $json['AppRetcode'] == 'QT100048'){
                    return ['code' => 1, 'text' => '鉴权失败，请重试'];
                }elseif($json['Status'] == 'F' && $json['AppRetcode'] == 'QT100025'){
                    return ['code' => 1, 'text' => '短信验证码不符，请重新确认'];
                }elseif($json['Status'] == 'P'){
                    return ['code' => 0, 'text' => '请求成功'];
                }else{
                    return ['code' => 1, 'text' => '用户状态异常'];
                }
            }elseif($customer == '3'){
                $rec = $request->all();
                $huicao['account_no'] = $rec['verify_bankcard_no'];
                $huicao['auth_type'] = 4;
                $huicao['cert_no'] = $rec['verify_idcard_no'];
                $huicao['mch_no'] = env('HUICAO_JUHE_MERCHANNO');
                $huicao['mobile'] = $rec['verify_bankcard_mobile'];
                $huicao['name'] = $rec['verify_name'];
                $huicao['request_time'] = time();
                $huicao['result_type'] = '';
                $huicao['tunnel'] = 1;
                $verify_arr = $this->rsaVerify($huicao);
                $sign = md5($verify_arr.'&key='.env('HUICAO_JUHE_KEY'));//签名
                $bind_nu = Redis::GET($huicao['account_no']);

                if($bind_nu >= 1){
                    return ['code' => 0, 'text' => '绑定成功'];
                }
                $params = [
                    'query' => [
                        'account_no' => $huicao['account_no'],
                        'auth_type' => 4,
                        'cert_no' => $huicao['cert_no'],
                        'mch_no' => $huicao['mch_no'],
                        'mobile' => $huicao['mobile'],
                        'name' => $huicao['name'],
                        'request_time' => $huicao['request_time'],
                        'result_type' => $huicao['result_type'],
                        'tunnel' => $huicao['tunnel'],
                        'sign' => $sign,
                    ]
                ];

                $url = 'http://auth.yifubank.com/api/mch/authCheck';
                $res = $this->guzzle($url, $params);
                $response = json_decode($res->getBody()->getContents(), true);
                if($response['status']){
                    //接通jcz
                    $send_url = env('OTHER_API').'/api/bindCard';
                    $params = [
                        'form_params' => [
                            'sign' => env('SIGN'),
                            'uid' => $uid,
                        ]
                    ];
                    try{
                        $res = $this->guzzle($send_url, $params);
                        $response = json_decode($res->getBody()->getContents(), true);
                        @file_put_contents('../storage/logs/define_bindcard_charge_'.date('Ym').'.log', date('Y-m-d H:i:s').'||post='.$params.'||res='.json_encode($response).'user_id='.$uid.PHP_EOL, FILE_APPEND);
                    }catch (\Exception $ex){
                        @file_put_contents('../storage/logs/defined_bind_card_exception_'.date('Ym').'.txt', $ex->getMessage().'||user_id='.$uid.'||date='.date('Y-m-d H:i:s'), FILE_APPEND);
                        return ['code' => 1, 'text' => '服务器异常，绑卡失败!'];
                    }
                    Redis::SETEX($huicao['account_no'],86400,1);
                    $user->bankcard_ok = 1;
                    $user->save();
                    return ['code' => 0, 'text' => '绑卡成功'];
                }else{
                    return ['code' => -1, 'text' => $response['data']];
                }
            }
        }
    }
    //绑卡-富友
    public function v2_bindCard(Request $request) {
        $return['code'] = -1;
        $return['text'] = '失败';
        $vcode = $request->input('vcode','');
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        $user = User::select(['id', 'channel_id', 'mobile','name','avatar','score','verify_name','verify_idcard_no','verify_bankcard_no','verify_bankcard_mobile','changjie_protocol_no','verify_idcard1_url','verify_idcard2_url','verify_alive_url','idcard_ok','alive_ok','bankcard_ok','sesamecredit_ok','emergency_contact_ok','company_ok','carrier_ok','taobaoweb_ok','emergency_contact1_type','emergency_contact1_name','emergency_contact1_mobile','emergency_contact2_type','emergency_contact2_name','emergency_contact2_mobile','company_name','company_address','company_tel','state','convert','created_at','updated_at'])->where("id","=",$uid)->first();
        $fuiou_MCHNTSSN = trim(session("fuiou_MCHNTSSN"));
        if(empty($vcode)) {
            $return['text'] = '请输入验证码';
            return $return;
        }
        if(!empty($user) && $logined == 1 && !empty($fuiou_MCHNTSSN) && !empty($vcode)) {
            $verify_bankcard_no = trim($request->input('verify_bankcard_no',''));
            $verify_bankcard_mobile = trim($request->input('verify_bankcard_mobile',''));
            $vcode = trim($request->input('vcode',''));
            $verify_name = $user->verify_name;
            $verify_idcard_no = $user->verify_idcard_no;
            $auto = 1;
            if($auto == 1) {
                if(!empty($verify_name) && !empty($verify_idcard_no) && !empty($verify_bankcard_no) && !empty($verify_bankcard_mobile)) {
                    //请求接口进行认证和扣费
                    $url = env('OTHER_API').'/api/bindCard';
                    $params = [
                        'form_params' => [
                            'verify_bankcard_no' => $verify_bankcard_no,
                            'verify_idcard_no' => $verify_idcard_no,
                            'fuiou_mchntssn' => $fuiou_MCHNTSSN,
                            'verify_name' => $verify_name,
                            'verify_bankcard_mobile' => $verify_bankcard_mobile,
                            'fuioumchntch' => $this->fuiouMchntcd,
                            'fuioumchntkey' => $this->fuiouMchntKey,
                            'vcode' => $vcode,
                            'sign' => env('SIGN'),
                            'uid' => $uid
                        ]
                    ];
                    try{
                        $bind_res = $this->guzzle($url, $params);
                        $bind_response = $bind_res->getBody()->getContents();
                        $bind_decode = json_decode($bind_response, true);
                        if($bind_decode['code']) return ['text' => $bind_decode['text']];
                    }catch (\Exception $e){
                        file_put_contents('./bindcard.txt', $e->getMessage(), FILE_APPEND);
                    }
                    $bind_result = json_decode($bind_response, true);
                    $yearMonth = $bind_result['yearMonth'];
                    $xml = $bind_result['xml'];
                    $jsonArray = $bind_result['jsonArray'];
                    $options = $bind_result['options'];

                    @file_put_contents('../storage/logs/transfer_bind_' . $yearMonth . '.log',  "\nXML:" . $xml  . "\nRES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                    if(!empty($jsonArray) && $jsonArray['RESPONSECODE'] == '0000') {
                        @file_put_contents('../storage/logs/transfer_bind_success_' . $yearMonth . '.log',  $url . "\nPOST:" . json_encode($options) . "\nRES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                        $return['code'] = 0;
                        $return['text'] = '绑定成功';
                        $user->changjie_protocol_no = $jsonArray['PROTOCOLNO'];
                        $user->verify_bankcard_no = $verify_bankcard_no;
                        $user->verify_bankcard_mobile = $verify_bankcard_mobile;
                        $user->bankcard_ok = 1;
                        $user->save();
                    }  else {
                        //$return['text'] = json_encode($jsonArray);
                        $return['text'] = $jsonArray['RESPONSEMSG'];
                    }
                } else {
                    $return['text'] = "失败2";
                }
            }
        }
        return $return;
    }

    public function guzzle($url, $params)
    {
        $client = new GuzzleClient([
            // 超时
            'timeout' => 120.0,
        ]);
        return $client->request('POST', $url, $params);
    }

    //银行卡解绑-富友
    public function v1_unbindCard(Request $request) {

        $return['code'] = -1;
        $return['text'] = '失败';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        $user = User::select(['id', 'channel_id', 'mobile','name','avatar','score','verify_name','verify_idcard_no','verify_bankcard_no','verify_bankcard_mobile','changjie_protocol_no','verify_idcard1_url','verify_idcard2_url','verify_alive_url','idcard_ok','alive_ok','bankcard_ok','sesamecredit_ok','emergency_contact_ok','company_ok','carrier_ok','taobaoweb_ok','emergency_contact1_type','emergency_contact1_name','emergency_contact1_mobile','emergency_contact2_type','emergency_contact2_name','emergency_contact2_mobile','company_name','company_address','company_tel','state','convert','created_at','updated_at'])->where("id","=",$uid)->first();
        if(!empty($user) && $logined == 1) {
            $changjie_protocol_no = $user->changjie_protocol_no;
            if(!empty($changjie_protocol_no)) {
                #调用接口
                $VERSION = "1.00";
                $MCHNTCD = $this->fuiouMchntcd;
                $mchntkey =  $this->fuiouMchntKey;
                $USERID = $uid;
                $PROTOCOLNO = $changjie_protocol_no;
                $str = "$VERSION|$MCHNTCD|$USERID|$PROTOCOLNO|$mchntkey";
                $SIGN = md5($str);
                $SIGN = strtoupper($SIGN);
                $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <REQUEST> <VERSION>$VERSION</VERSION> <MCHNTCD>$MCHNTCD</MCHNTCD> <USERID>$USERID</USERID> <PROTOCOLNO>$PROTOCOLNO</PROTOCOLNO> <SIGN>$SIGN</SIGN> </REQUEST>";

                $size = mcrypt_get_block_size('des','ecb');
                $input = self::pkcs5_pad($xml, $size);
                $td = mcrypt_module_open('des', '', 'ecb', '');
                $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
                @mcrypt_generic_init($td, $mchntkey, $iv);
                $data = mcrypt_generic($td, $input);
                mcrypt_generic_deinit($td);
                mcrypt_module_close($td);
                $APIFMS = base64_encode($data);

                $list=array("MCHNTCD" => $MCHNTCD,"APIFMS" => $APIFMS);
                $url="https://mpay.fuioupay.com/newpropay/unbind.pay";
                $query = http_build_query($list);
                $options = array(
                    'http' => array(
                        'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                            "Content-Length: ".strlen($query)."\r\n".
                            "User-Agent:MyAgent/1.0\r\n",
                        'method'  => "POST",
                        'content' => $query,
                    ),
                );
                $yearMonth = date("Ym");
                @file_put_contents('../storage/logs/unbind_' . $yearMonth . '.log', $url . "\nPOST:" . json_encode($xml) . "\n" . json_encode($options) . "\n" ,FILE_APPEND);
                $context = stream_context_create($options);
                $result = file_get_contents($url, false, $context, -1, 40000);

                $input = base64_decode($result);
                $size = mcrypt_get_block_size('des','ecb');
                $td = mcrypt_module_open('des', '', 'ecb', '');
                $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
                @mcrypt_generic_init($td, $mchntkey, $iv);
                $data = mdecrypt_generic($td, $input);
                mcrypt_generic_deinit($td);
                mcrypt_module_close($td);
                $data = self::pkcs5_unpad($data, $size);

                $postObj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);

                $jsonStr = json_encode($postObj);
                $jsonArray = json_decode($jsonStr,true);

                @file_put_contents('../storage/logs/transfer_unbind_' . $yearMonth . '.log',  "RES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                if(!empty($jsonArray) && $jsonArray['RESPONSECODE'] == '0000') {
                    @file_put_contents('../storage/logs/transfer_unbind_success_' . $yearMonth . '.log',  $url . "\nPOST:" . json_encode($options) . "\nRES:" . json_encode($jsonArray)  . "\n\n" ,FILE_APPEND);
                    $user->changjie_protocol_no = '';
                    $user->bankcard_ok = 0;
                    $user->save();
                    $return['code'] = 0;
                    $return['text'] = '解绑成功';
                } else {
                    $return['text'] = $jsonArray['RESPONSEMSG'] . "-$changjie_protocol_no";
                }
            }
        }
        return $return;
    }


    /**
     * @param Request $request
     * @return mixed
     *  活体检测预订单
     */
    //安
    public function bizpreorder(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $return['data'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $user = User::select("id",'mobile','verify_name','verify_idcard_no')->where("id","=",$uid)->first();
            if(!empty($user)) {
                $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
                require_once($path);
                //echo "$path";exit();
                $txn_type= '03304';
                $trans_id = BaofooUtils::create_uuid();//商户订单号
                $trade_date = BaofooUtils::trade_date();//交易时间
                $arrayData=array(
                    "member_id" => $member_id,
                    "terminal_id" => $terminal_id,
                    "trans_id" => $trans_id,
                    "trade_date" => $trade_date,
                    "source" => "SDK",
                    "txn_type" => $txn_type,
                    "industry_type"=>"A1"//根据自己的行业类型传入
                );
                // *** 数据格式化***
                $data_content="";
                //==================转换数据类型=============================================
                if($data_type == "json"){
                    $data_content = str_replace("\\/", "/",json_encode($arrayData));//转JSON
                }
                //echo $data_content;
                // **** 先BASE64进行编码再RSA加密 ***
                $BFRsa = new BFRSA($pfxpath, $cerpath, $pfx_pwd,TRUE); //实例化加密类。
                $data_content = $BFRsa->encryptedByPrivateKey($data_content);
                Log::LogWirte("====加密串".$data_content);
                /**============== http 请求==================== **/
                $request_url = $cardAuthUrl;
                $PostArry = array(
                    "member_id" => $member_id,
                    "terminal_id" => $terminal_id,
                    "data_type" => $data_type,
                    "data_content" => $data_content);
                $request_url = "https://api.xinyan.com/biz/score/v1/preOrder";//请求地址
                @file_put_contents('../storage/logs/bizpreorder.log', $request_url . "\n" . json_encode($PostArry) . "\n" ,FILE_APPEND);
                $reslut = HttpClient::Post($PostArry, $request_url);  //发送请求到服务器，并输出返回结果。
                @file_put_contents('../storage/logs/bizpreorder.log' , "\nRES：" . $reslut . "\n\n" ,FILE_APPEND);
                $arr = json_decode($reslut,true);
                if(isset($arr['success'])) {
                    if($arr['success'] == true) {
                        $return['code'] = 0;
                        $return['data'] = $arr['data'];
                        $return['data']['id_name'] = $user['verify_name'];
                        $return['data']['id_no'] = $user['verify_idcard_no'];
                        $return['data']['appkey'] = $biz_pfx_pwd;
                    } else {
                        $return['text'] = $arr['errorMsg'];
                    }
                }
            }
        }
        return $return['data'];
    }

    /**
     * @param Request $request
     * @return mixed
     * 活体检测状态更新*/
    //安
    public function updateAlive(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '认证失败';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if(!empty($uid) && $logined == 1) {
            $trans_id = trim($request->input('trans_id',''));
            $tradeNo = trim($request->input('tradeNo',''));
            $content = trim($request->input('content',''));
            $faceBase64 = trim($request->input('faceBase64',''));
            $user = User::select("id")->where("id","=",$uid)->first();
            if(!empty($user)) {
                $md5str = md5(md5($trans_id.$tradeNo.$this->md5key));
                if($md5str == $content) {
                    $user->alive_ok = 1;

                    $disk = QiniuStorage::disk('qiniu');
                    $filename = "face_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($faceBase64)); //上传文件
                    $domain = config('filesystems.disks.qiniu.domain');
                    $verify_alive_url = "http://$domain/$filename";
                    $user->verify_alive_url = $verify_alive_url;
                    $user->save();
                    $return['code'] = 0;
                    $return['text'] = '认证成功';
                    $return['verifyAliveUrl'] = $verify_alive_url;
                }
            }
        }
        return $return;
    }

    public function logout(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '失败';
        $uid = intval(session("uid"));
        if (!empty($uid)) {
            $session['logined'] = 0;
            $session['uid'] = 0;
            $session['openid'] = '';
            $session['name'] = '';
            $session['avatar'] = '';
            session($session);
            $return['code'] = 0;
            $return['text'] = '登出成功';
        }
        return $return;

    }
    //有盾身份认证回调
    public function udid_notify(Request $request) {
        $authKey = "5ae3209e-0b2f-49c0-a6dc-5bb639f32cca";
        //商户security_key： 开户时通过邮件发送给商户
        $secretKey = "6ba6dba0-5ff0-4fa9-90f8-2816faae4842";
        $return['code'] = -1;
        $return['text'] = '失败';
        $postStr = $request->getContent();
        if(isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        }
        @file_put_contents("../storage/logs/user_udid_notify_".date('Ymd').".log", date("Y-m-d H:i:s") . "\n" . $_SERVER['REQUEST_URI'] . "\n" . $_SERVER["QUERY_STRING"]  . "\npostdata:" . mb_substr($postStr, 0, 300, 'utf-8'). PHP_EOL, FILE_APPEND);
        $arr = json_decode($postStr,true);
        if(!empty($arr)) {
            $sign =  $arr['sign'];
            $partner_order_id =  $arr['partner_order_id'];
            $sign_time =  $arr['sign_time'];
            $mysing = "pub_key=$authKey|partner_order_id=$partner_order_id|sign_time=$sign_time|security_key=$secretKey";
            $mysing = strtoupper(md5($mysing));
            $uidarr = explode("_",$partner_order_id);
            //判断是否是重复回调
            $udid_notify_key = "udid_notify";
            $udid_notified = Redis::HGET($udid_notify_key,$partner_order_id);
            if($mysing == $sign && !empty($uidarr) && empty($udid_notified)) {
                $uid = $uidarr[0];
                $user = User::where("id",$uid)->first();
                if(!empty($user)) {
                    $disk = QiniuStorage::disk('qiniu');
                    $domain = config('filesystems.disks.qiniu.domain');

                    $filename = "face_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($arr['living_photo'])); //上传文件
                    $verify_alive_url = "http://$domain/$filename";

                    $filename = "idcard1_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($arr['idcard_front_photo'])); //上传文件
                    $verify_idcard1_url = "http://$domain/$filename";

                    $filename = "idcard2_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($arr['idcard_back_photo'])); //上传文件
                    $verify_idcard2_url = "http://$domain/$filename";

                    //回调自增,防止重复回调
                    Redis::HINCRBY($udid_notify_key,$partner_order_id,1);

                    $send_url = env('OTHER_API').'/api/realmsg';
                    $params = [
                        'form_params' => [
                            'sign' => env('SIGN'),
                            'uid' => $uid
                        ]
                    ];
                    try{
                        $result_data = $this->guzzle($send_url, $params);
                        $reslut = $result_data->getBody()->getContents();
                        $bind_decode = json_decode($reslut, true);
                        if($bind_decode['code']) return ['text' => $bind_decode['text']];
                    }catch (\Exception $e){
                        @file_put_contents('../storage/logs/verify_user_name_error_'.date('Ym').'.log', $e->getMessage().'||user_id='.$uid.'||date='.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
                        return false;
                    }
                    @file_put_contents('../storage/logs/verify_user_name_'.date('Ymd').'.log', 'post='.json_encode($params).'||res='.json_encode($request).'||arr='.json_encode($arr).'||user_id='.$uid.'||date='.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
                    $user->verify_name = $arr['id_name'];
                    $user->verify_idcard_no = $arr['id_number'];
                    $user->verify_gender = $arr['gender'];
                    $user->age = $arr['age'];
                    $user->verify_idcard1_url = $verify_idcard1_url;
                    $user->verify_idcard2_url = $verify_idcard2_url;
                    $user->verify_alive_url = $verify_alive_url;
                    $user->idcard_ok = 1;
                    $user->alive_ok = 1;
                    $user->last_verify_vertification = date("Y-m-d H:i:s");
                    $user->save();
                    $return['code'] = 0;
                    $return['text'] = '认证成功';
                    $return['verify_idcard1_url'] = $verify_idcard1_url;
                    $return['verify_idcard2_url'] = $verify_idcard2_url;
                    $return['verify_alive_url'] = $verify_alive_url;
                }
            }
        }
        return $return;
    }
	//Linkface身份认证回调
    public function linkface_notify(Request $request) {
        $sign_key = "kfjs32329828kdfkddje212skksdkv55422e";
        $return['code'] = -1;
        $return['text'] = '失败';
		$postStr = $request->getContent();
        if(isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        }
		$encryTarData = $request->input('encryTarData','');
		$liveness_data_file = $request->input('liveness_data_file','');
		$selfie_image_base64 = $request->input('selfie_image_base64','');
        $sign_time = $request->input('sign_time','');
		$living_photo = $request->input('living_photo','');
		$idcard_front_photo = $request->input('idcard_front_photo','');
		$idcard_back_photo = $request->input('idcard_back_photo','');
		$id_name = $request->input('id_name','');
		$id_number = $request->input('id_number','');
		$gender = $request->input('gender','');
		$birthday = $request->input('birthday','');
		$sign = $request->input('sign','');
		$mysing = "id_name=$id_name|id_number=$id_number|gender=$gender|birthday=$birthday|sign_time=$sign_time|sign_key=$sign_key";
		
        @file_put_contents("../storage/logs/linkface_notify_".date('Ymd')."_1.log", date("Y-m-d H:i:s") . "\n" . $_SERVER['REQUEST_URI'] . "\n" . $_SERVER["QUERY_STRING"]  . "\nencryTarData:" .$encryTarData. " \npostdata:$mysing\nsign:$sign\n". PHP_EOL, FILE_APPEND);
		
		$uid = intval(session("uid"));
        if (!empty($uid)) {   
            $mysing = strtoupper(md5($mysing));
			// echo $mysing; 
            if($mysing == $sign) {
                $user = User::where("id",$uid)->first();
                if(!empty($user) && !empty($id_name) && !empty($id_number) && !empty($gender) && !empty($birthday) && !empty($living_photo) && !empty($idcard_front_photo) && !empty($idcard_back_photo)) {
                    $disk = QiniuStorage::disk('qiniu');
                    $domain = config('filesystems.disks.qiniu.domain');

                    $filename = "face_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($living_photo)); //上传文件
                    $verify_alive_url = "http://$domain/$filename";
					 
                    $filename = "idcard1_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($idcard_front_photo)); //上传文件
                    $verify_idcard1_url = "http://$domain/$filename";

                    $filename = "idcard2_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($idcard_back_photo)); //上传文件
                    $verify_idcard2_url = "http://$domain/$filename";
					
					$liveness_filename = $filename = "liveness_" . date("YmdHis") . rand(111111,999999). ".mp4"; 
                    $disk->put($filename,base64_decode($encryTarData)); //上传文件
                    $liveness_data_file_url = "http://$domain/$filename";

                    $send_url = env('OTHER_API').'/api/realmsg';
                    $params = [
                        'form_params' => [
                            'sign' => env('SIGN'),
                            'uid' => $uid
                        ]
                    ];
                    try{
                        $result_data = $this->guzzle($send_url, $params);
                        $reslut = $result_data->getBody()->getContents();
                        $bind_decode = json_decode($reslut, true);
                        if($bind_decode['code']) return ['text' => $bind_decode['text']];
                    }catch (\Exception $e){
                        @file_put_contents('../storage/logs/verify_user_name_error_'.date('Ym').'.log', $e->getMessage().'||user_id='.$uid.'||date='.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
                        return false;
                    }
                    @file_put_contents('../storage/logs/verify_user_name_'.date('Ymd').'.log', 'post='.json_encode($params).'||res='.json_encode($request).'||post='.json_encode($_POST).'||user_id='.$uid.'||date='.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);

					
					//linkface接口认证
					$url = 'https://cloudapi.linkface.cn/identity/selfie_idnumber_verification';
					$linkfaceparams['api_id'] = '733ef0761d704d5290951fbe4ca4e435';
					$linkfaceparams['api_secret'] = 'cc09abd2f7734fd29c2eda5154e1b512';
					$linkfaceparams['id_number'] = $id_number;  
					$linkfaceparams['name'] = $id_name;    
					$linkfaceparams['selfie_image_base64'] = $idcard_front_photo;
					@file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceparams:$id_name,$id_number\n". PHP_EOL, FILE_APPEND);
					//$linkfaceresult = $client->request('POST', $url, $linkfaceparams);
					$data_string = json_encode($linkfaceparams);
					$ch = curl_init($url);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
					curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(
						'Content-Type: application/json',
						'Content-Length: ' . strlen($data_string))
					);
					$linkfaceresult1 = curl_exec($ch);
					curl_close($ch);


					@file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceresult1:$linkfaceresult1". PHP_EOL, FILE_APPEND);
			
					$verify_alive_url_private = $disk->privateDownloadUrl($liveness_filename)->getUrl(); 
					$url = 'https://cloudapi.linkface.cn/identity/liveness_idnumber_verification';
					$linkfaceparams2['api_id'] = '733ef0761d704d5290951fbe4ca4e435';
					$linkfaceparams2['api_secret'] = 'cc09abd2f7734fd29c2eda5154e1b512';
					$linkfaceparams2['id_number'] = $id_number;  
					$linkfaceparams2['name'] = $id_name;    
					$linkfaceparams2['liveness_data_url'] = $verify_alive_url_private;
					@file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceparams2:$id_name,$id_number---\n$living_photo\n---". PHP_EOL, FILE_APPEND);
					//$linkfaceresult = $client->request('POST', $url, $linkfaceparams2);
					$data_string = json_encode($linkfaceparams2);
					$ch = curl_init($url);
					curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
					curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(
						'Content-Type: application/json',
						'Content-Length: ' . strlen($data_string))
					);
					$linkfaceresult2 = curl_exec($ch);
					curl_close($ch);
					//$verify_alive_url_private = str_replace("https","http://$domain",$verify_alive_url_private)
					//var_dump($linkfaceresult1);
					//
					$user->idcard_ok = 0;
					$user->alive_ok = 0;
					$linkfacearr1 = json_decode($linkfaceresult1,true);
					$linkfacearr2 = json_decode($linkfaceresult2,true);
					if(isset($linkfacearr1['status']) && isset($linkfacearr1['confidence']) && $linkfacearr1['status'] == 'OK' && $linkfacearr1['confidence'] > 0.8) {
						$return['confidence'] = $linkfacearr1['confidence'];
						
						if(isset($linkfacearr2['status']) && isset($linkfacearr2['verify_score']) && $linkfacearr2['status'] == 'OK' && $linkfacearr2['verify_score'] > 0.8) {  
							
							$return['code'] = 0;
							$return['text'] = '成功';
							$user->idcard_ok = 1;
							$user->alive_ok = 1;
							$return['verify_score'] = $linkfacearr2['verify_score'];
						}
					}
					
					@file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceresult2:$linkfaceresult2". PHP_EOL, FILE_APPEND);
 					
					list($birthYear, $birthMonth, $birthDay) = explode('-', $birthday);
					list($currentYear, $currentMonth, $currentDay) = explode('-', date('Y-m-d'));
					$age = $currentYear - $birthYear - 1;
					if($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay)
						$age++;
					$user->verify_name = $id_name;
                    $user->verify_idcard_no = $id_number;
                    $user->verify_gender = $gender;
                    $user->age = $age;
                    $user->verify_idcard1_url = $verify_idcard1_url;
                    $user->verify_idcard2_url = $verify_idcard2_url;
                    $user->verify_alive_url = $verify_alive_url;
                    
                    $user->last_verify_vertification = date("Y-m-d H:i:s");
                    $user->save();
                    
                    //$return['verify_idcard1_url'] = $verify_idcard1_url;
                    //$return['verify_idcard2_url'] = $verify_idcard2_url;
                    //$return['verify_alive_url'] = $verify_alive_url;


                } else {
					$return['text'] = '失败：0002';
				}
            } else {
				$return['text'] = '失败：0001';
			}
        }
        return $return;
    }

    //linckface的活体检测的回调
    public function linkface_liveness_notify(Request $request){
        $sign_key = "kfjs32329828kdfkddje212skksdkv55422e";
        $return['code'] = -1;
        $return['text'] = '失败';
        $postStr = $request->getContent();
        if(isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        }
        $encryTarData = $request->input('encryTarData','');
        $liveness_data_file = $request->input('liveness_data_file','');
        $selfie_image_base64 = $request->input('selfie_image_base64','');
        $sign_time = $request->input('sign_time','');
        $living_photo = $request->input('living_photo','');
        $idcard_front_photo = $request->input('idcard_front_photo','');
        $idcard_back_photo = $request->input('idcard_back_photo','');
        $id_name = $request->input('id_name','');
        $id_number = $request->input('id_number','');
        $gender = $request->input('gender','');
        $birthday = $request->input('birthday','');
        $sign = $request->input('sign','');
        $mysing = "id_name=$id_name|id_number=$id_number|gender=$gender|birthday=$birthday|sign_time=$sign_time|sign_key=$sign_key";

        @file_put_contents("../storage/logs/linkface_notify_".date('Ymd')."_1.log", date("Y-m-d H:i:s") . "\n" . $_SERVER['REQUEST_URI'] . "\n" . $_SERVER["QUERY_STRING"]  . "\nencryTarData:" .$encryTarData. " \npostdata:$mysing\nsign:$sign\n". PHP_EOL, FILE_APPEND);

        $uid = intval(session("uid"));
        if (!empty($uid)) {
            $mysing = strtoupper(md5($mysing));
            // echo $mysing;
            if($mysing == $sign) {
                $user = User::where("id",$uid)->first();
                if(!empty($user) && !empty($id_name) && !empty($id_number) && !empty($gender) && !empty($birthday) && !empty($living_photo) && !empty($idcard_front_photo) && !empty($idcard_back_photo)) {
                    $disk = QiniuStorage::disk('qiniu');
                    $domain = config('filesystems.disks.qiniu.domain');

                    $filename = "face_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($living_photo)); //上传文件
                    $verify_alive_url = "http://$domain/$filename";

                    $filename = "idcard1_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($idcard_front_photo)); //上传文件
                    $verify_idcard1_url = "http://$domain/$filename";

                    $filename = "idcard2_" . date("YmdHis") . rand(111111,999999). ".jpg";
                    $disk->put($filename,base64_decode($idcard_back_photo)); //上传文件
                    $verify_idcard2_url = "http://$domain/$filename";

                    $liveness_filename = $filename = "liveness_" . date("YmdHis") . rand(111111,999999). ".mp4";
                    $disk->put($filename,base64_decode($encryTarData)); //上传文件
                    $liveness_data_file_url = "http://$domain/$filename";
                    

                    //linkface接口认证
                    $url = 'https://cloudapi.linkface.cn/identity/selfie_idnumber_verification';
                    $linkfaceparams['api_id'] = '733ef0761d704d5290951fbe4ca4e435';
                    $linkfaceparams['api_secret'] = 'cc09abd2f7734fd29c2eda5154e1b512';
                    $linkfaceparams['id_number'] = $id_number;
                    $linkfaceparams['name'] = $id_name;
                    $linkfaceparams['selfie_image_base64'] = $idcard_front_photo;
                    @file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceparams:$id_name,$id_number\n". PHP_EOL, FILE_APPEND);
                    //$linkfaceresult = $client->request('POST', $url, $linkfaceparams);
                    $data_string = json_encode($linkfaceparams);
                    $ch = curl_init($url);
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                            'Content-Type: application/json',
                            'Content-Length: ' . strlen($data_string))
                    );
                    $linkfaceresult1 = curl_exec($ch);
                    curl_close($ch);


                    @file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceresult1:$linkfaceresult1". PHP_EOL, FILE_APPEND);

                    $verify_alive_url_private = $disk->privateDownloadUrl($liveness_filename)->getUrl();
                    $url = 'https://cloudapi.linkface.cn/identity/liveness_idnumber_verification';
                    $linkfaceparams2['api_id'] = '733ef0761d704d5290951fbe4ca4e435';
                    $linkfaceparams2['api_secret'] = 'cc09abd2f7734fd29c2eda5154e1b512';
                    $linkfaceparams2['id_number'] = $id_number;
                    $linkfaceparams2['name'] = $id_name;
                    $linkfaceparams2['liveness_data_url'] = $verify_alive_url_private;
                    @file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceparams2:$id_name,$id_number---\n$living_photo\n---". PHP_EOL, FILE_APPEND);
                    //$linkfaceresult = $client->request('POST', $url, $linkfaceparams2);
                    $data_string = json_encode($linkfaceparams2);
                    $ch = curl_init($url);
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                            'Content-Type: application/json',
                            'Content-Length: ' . strlen($data_string))
                    );
                    $linkfaceresult2 = curl_exec($ch);
                    curl_close($ch);
                    //$verify_alive_url_private = str_replace("https","http://$domain",$verify_alive_url_private)
                    //var_dump($linkfaceresult1);
                    //
                    $user->idcard_ok = 0;
                    $user->alive_ok = 0;
                    $linkfacearr1 = json_decode($linkfaceresult1,true);
                    $linkfacearr2 = json_decode($linkfaceresult2,true);
                    if(isset($linkfacearr1['status']) && isset($linkfacearr1['confidence']) && $linkfacearr1['status'] == 'OK' && $linkfacearr1['confidence'] > 0.8) {
                        $return['confidence'] = $linkfacearr1['confidence'];

                        if(isset($linkfacearr2['status']) && isset($linkfacearr2['verify_score']) && $linkfacearr2['status'] == 'OK' && $linkfacearr2['verify_score'] > 0.8) {

                            $return['code'] = 0;
                            $return['text'] = '成功';
                            $user->idcard_ok = 1;
                            $user->alive_ok = 1;
                            $return['verify_score'] = $linkfacearr2['verify_score'];
                        }
                    }

                    @file_put_contents("../storage/logs/linkface_notify_".date('Ymd').".log","linkfaceresult2:$linkfaceresult2". PHP_EOL, FILE_APPEND);

                    list($birthYear, $birthMonth, $birthDay) = explode('-', $birthday);
                    list($currentYear, $currentMonth, $currentDay) = explode('-', date('Y-m-d'));
                    $age = $currentYear - $birthYear - 1;
                    if($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay)
                        $age++;
                    $user->verify_name = $id_name;
                    $user->verify_idcard_no = $id_number;
                    $user->verify_gender = $gender;
                    $user->age = $age;
                    $user->verify_idcard1_url = $verify_idcard1_url;
                    $user->verify_idcard2_url = $verify_idcard2_url;
                    $user->verify_alive_url = $verify_alive_url;

                    $user->last_verify_vertification = date("Y-m-d H:i:s");
                    $user->save();

                    //$return['verify_idcard1_url'] = $verify_idcard1_url;
                    //$return['verify_idcard2_url'] = $verify_idcard2_url;
                    //$return['verify_alive_url'] = $verify_alive_url;


                } else {
                    $return['text'] = '失败：0002';
                }
            } else {
                $return['text'] = '失败：0001';
            }
        }
        return $return;
    }

    //统计UV时前端请求的接口
    protected function uvstatistic($request, $cookie_remark, $real_cid){
        $server = $_SERVER;

        $url = 'http://'.$server['HTTP_HOST'];
        $referer = empty($server['HTTP_REFERER'])?'':$server['HTTP_REFERER'];
        $keyword = '';
        $guid = 'uvnum='.$cookie_remark;
        $ip = $server['REMOTE_ADDR'];
        $cookie = '666';
        $province = '';
        $city = '';
        $platform = '';
        $version = $server['HTTP_USER_AGENT'];
        $channelid = $real_cid;
        $serverid = env('BSIGN');

        $send_url = env('RISKDECISION')."/easyuseapi/user/track/savepage";
        $params = [
            'json' => [
                'url' => $url,
                'referer' => $referer,
                'keyword' => $keyword,
                'guid' => $guid,
                'ip' => $ip,
                'cookie' => $cookie,
                'province' => $province,
                'city' => $city,
                'platform' => $platform,
                'version' => $version,
                'channelid' => $channelid,
                'serverid' => $serverid
            ],
            'headers' => [
                'ident' => 'production'
            ]
        ];
        try{
            $response = $this->guzzle($send_url, $params);
            $res = json_decode($response->getBody()->getContents(), true);
            @file_put_contents('../storage/logs/uvstatistic_push_'.date('Ymd').'.log', 'date='.date('Y-m-d H:i:s').'||post='.json_encode($params).'||res='.json_encode($res).PHP_EOL, FILE_APPEND);
        }catch (\Exception $exc){
            @file_put_contents('../storage/logs/uvstatistic_push_excepton_'.date('Ymd').'.log', 'date='.date('Y-m-d H:i:s').'||post='.json_encode($params).PHP_EOL, FILE_APPEND);
        }
    }

    //判断用户是否需要验证码
    public function ishasCode(Request $request){
        $username = $request->post('username');
        $isopen = AdminUser::where('username', $username)->value('isopen');
        if($isopen == 2){
            return ['code' => 1, 'info' => '需要验证码'];
        }else{
            return ['code' => 0, 'info' => '不需要验证码'];
        }
    }
    //运营商认证返回地址
    public function carrier_back(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $user = User::select("id",'mobile')->where("id","=",$uid)->first();
        if(!empty($user)) {
            $user->last_verify_carrier = date("Y-m-d H:i:s");
            $user->save();
            return redirect("/html/verify.html");
        }
    }
    //用于模型分和可以设备的导入
    public function moxin_keyi(){
        $orders = Order::with('user')->where('finished_at', ' ')->where('repayment_at', '<>', ' ')->where('repayment_at', '<', date('Y-m-d').' 00:00:00')->get();
//        echo '<pre>';
//        var_dump(count($orders));
//        die;
        foreach ($orders as $key => $val){
            $mobile = $val->user->mobile;
            $id_no = $val->user->verify_idcard_no;
            $order_no = $val->out_trade_no;
            $send_url = env('RISKDECISION')."/easyuseapi/riskreport/GetGeneralReport";
            $params = [
                'query' => [
                    'user_id' => env('BSIGN'),
                    'mobile' => $mobile,
                    'id_no' => $id_no,
                    'order_no' => $order_no,
                    'days' => 3
                ],
                'headers' => [
                    'ident' => 'production'
                ]
            ];
            $res = $this->guzzle($send_url, $params);
            $response = json_decode($res->getBody()->getContents(), true);
//            echo '22';
//            dd($response);
//            die;
            $help_order = new HelpTable();
            $help_order->out_trade_no = $order_no;
            $help_order->daimo = $response['data']['id_detail']['score'];//贷前模型
            $help_order->keyi = $response['data']['user_features'][5]['value'];//可疑设备
            $help_order->pintai = $response['data']['device_summary'][6]['value'];//设备申请借款平台数

            $help_order->zjsqjkapp = $response['data']['request_info_app'][0]['value'];//总计申请借款app数
            $help_order->sbsqjkpts = $response['data']['loan_detail'][0]['value'];//申请借款平台数
            $help_order->save();
        }
    }

    public function export_moxin_keyi(){
        $orders = Order::with('user', 'helpTables')->where('finished_at', ' ')->where('repayment_at', '<>', ' ')->where('repayment_at', '<', date('Y-m-d').' 00:00:00')->get();
        $cellData[] = ['姓名','手机号','身份证号','行为分','准入分','置信分','贷前模型', '可疑设备', '设备申请借款平台数', '总计申请借款app数', '申请借款平台', '逾期时间'];
        foreach ($orders as $key => $val){
            $cell_tab['verify_name'] = $val->user->verify_name;
            $cell_tab['mobile'] = $val->user->mobile;
            $cell_tab['verify_idcard_no'] = $val->user->verify_idcard_no;
            $cell_tab['score'] = $val->user->score;
            $cell_tab['br_score'] = $val->user->br_score;
            $cell_tab['risk_score'] = $val->risk_score;//置信分
            $cell_tab['daimo'] = $val->helpTables->daimo;//贷后模型
            $cell_tab['keyi'] = $val->helpTables->keyi;//可以设备
            $cell_tab['pintai'] = $val->helpTables->pintai;//设备申请借款平台数

            $cell_tab['zjsqjkapp'] = $val->helpTables->zjsqjkapp;//总计申请借款app数
            $cell_tab['sbsqjkpts'] = $val->helpTables->sbsqjkpts;//申请借款平台数

            $current = strtotime(date('Y-m-d').' 23:59:59');
            $repayment = $val->repayment_at;
            $repayment_day = strtotime(date('Y-m-d', strtotime($repayment)).' 23:59:59');
            $cell_tab['over_day'] =  ($current - $repayment_day) / 86400;
            $cellData[] = $cell_tab;
        }
        $this->export($cellData);
    }
    //导出方法
    public function export($cellData){
        //创建excel文件（文件名,excel的实例 use 需要使用的数据）
        Excel::create(sha1(time() . rand(1000,9999)),function($excel) use ($cellData){
            //创建工作表（工作表名称,工作表的实例 use 需要使用的数据）
            $excel->sheet('数据库', function($sheet) use ($cellData){
                //行数据
                $sheet -> rows($cellData);
            });
        }) -> export('xls');
    }

    //获取综合报告
    public function general_report(Request $request){
        $rec = $request->all();
        $mobile = $rec['mobile'];
        $id_no = $rec['id_no'];
        $order_no = $rec['order_no'];
        $send_url = env('RISKDECISION')."/easyuseapi/riskreport/GetGeneralReport";
        $params = [
            'query' => [
                'user_id' => env('BSIGN'),
                'mobile' => $mobile,
                'id_no' => $id_no,
                'order_no' => $order_no,
                'days' => 3
            ],
            'headers' => [
                'ident' => 'production'
            ]
        ];

        //获取用户在准入分和置信分
        $order = Order::where('out_trade_no', $order_no)->first();
        if(count($order)){
            $other['br_score'] = $order->br_score ?? 0;
            $other['px_score'] = $order->risk_score ?? 0;
            $passtype = $order->passtype ?? 0;
            $state = $order->state ?? 0;
            $passtype_arr = config('common.order_status');;
            $other['order_type'] = $passtype_arr[$passtype] ?? '复审';

            $statearr = config('common.order_status');

            if ($passtype == 11) {
                $other['order_state'] = '初审拒绝';
            }
            if ($state != 4) {
                $repayment_time = $order->repayment_at ?? '';
                if (!empty($repayment_time) && date('Y-m-d', strtotime($repayment_time)) == date('Y-m-d')) {
                    $other['order_state'] = '待还款';
                }
                $other['order_state'] = $statearr[$state] ?? '复审';
            } else {
                $other['order_state'] = $passtype_arr[$passtype] ?? '复审';
            }
        }else{
            $user_order = User::with('order', 'order.bairongDecision')->where('mobile', $mobile)->first();
            $order_count = count($user_order->order);
            if($order_count){
                $order = $user_order->order[$order_count - 1];
                $other['br_score'] = $order->br_score ?? 0;
                $other['px_score'] = $order->risk_score ?? 0;
                $passtype = $order->passtype ?? 0;
                $state = $order->state ?? 0;
                $passtype_arr = config('common.order_status');
                $other['order_type'] = $passtype_arr[$passtype];

                $statearr = config('common.order_status');

                if ($passtype == 11) {
                    $other['order_state'] = '初审拒绝';
                }
                if ($state != 4) {
                    $repayment_time = $order->repayment_at ?? '';
                    if (!empty($repayment_time) && date('Y-m-d', strtotime($repayment_time)) == date('Y-m-d')) {
                        $other['order_state'] = '待还款';
                    }
                    $other['order_state'] = $statearr[$state];
                } else {
                    $other['order_state'] = $passtype_arr[$passtype];
                }
            }else{
                $other['order_state'] = '未下单';
                $other['order_type'] = '未下单';
                $other['br_score'] = 0;
                $other['px_score'] = 0;
            }
        }

        try{
            $res = $this->guzzle($send_url, $params);
            $response = json_decode($res->getBody()->getContents(), true);
            file_put_contents('../storage/logs/general_report_'.date('Ym').'.log', 'date='.date('Y-m-d H:i:s').'||post='.json_encode($params).'||res='.json_encode($response), FILE_APPEND);
            if($response['rspCode'] == 0){
                $common_obj = new AdminCommonController();
                $detail = '查看了客户'.$mobile.'的征信报告';
                $common_obj->black_logoperation($detail);
                return ['code' => 0, 'otherdata' => $other,  'data' => $response['data']];
            }else{
                return ['code' => 1, 'text' => '没有数据返回', 'data' => $response];
            }
        }catch (\Exception $ex){
            file_put_contents('../storage/logs/general_report_notify_'.date('Ym').'.log', 'date='.date('Y-m-d H:i:s').'||post='.json_encode($params).'||res='.json_encode($ex->getMessage()), FILE_APPEND);
            return ['code' => 1, 'text' => '请求异常'];
        }

    }
    //借款协议
    public function borrow_protocol(){

        //选择调用的支付接口,从文件缓存里取数据
        $product_base = $this->product_config();
        $product_name = $product_base['appname'];

        $uid = session('uid');
        $user = User::with('channel.product')->where('id', $uid)->first();
        $product_type = $user->channel->product->product_type;
        $channel_id = $user->channel->id;

        $product_data = Channel::withTrashed()->with(['product' => function($query){
            $query->withTrashed();
        }])->where('id', $channel_id)->first();

        $order_obj = new OrderController();
        if($product_type == 1){
            $borrow_res = $order_obj -> extend_charge_upgrade($product_data, $user);
        }elseif($product_type == 2){
            $borrow_res = $order_obj -> extend_charge_upgrade_divide($product_data, $user);
        }

        $data['ContractNO'] = $this->pinyin_long($product_name).date('Ymd').time();//合同编号
        $data['AddTime'] = date('Y-m-d H:i:s');//签订日期
        $data['Lender'] = $product_name;//甲方（出借方）
        $data['Borrower'] = $user->verify_name;//乙方（借款方）
        $data['BIdenty'] = $user->verify_idcard_no;//身份证号
        $data['BMobile'] = $user->mobile;//手机号码
        $data['loanTime'] = date('Y-m-d H:i:s');//借款日期
        $data['Principal'] = $borrow_res['real_fee']/100;//借款本金

        $data['term'] = $borrow_res['days'];//借款期限

        $data['Interest'] = $data['Principal'] * round($user->channel->product->rate/100, 2) * $data['term'];//利息

        $borrow_res['verification_fee'] = $borrow_res['verification_fee'] ??  0;

        $data['Userfee'] = $borrow_res['verification_fee']/100;//账户管理费
        $data['repayTime'] = date('Y-m-d H:i:s', time() + $borrow_res['days'] * 86400);//应还日期
        $data['repayMoney'] = $borrow_res['max_money']/100 + $data['Interest'];//应还金额
        $data['overFee'] = $borrow_res['default_interest']/100;//逾期管理费

        $product_config = ProductConfig::select('borrowprotocol')->first();
        $data['protocol_text'] = $product_config->borrowprotocol;

        return $data;
    }
    //电子合同
    public function ele_order(Request $request){
        $data = $request->all();
        $oid = $data['oid'];
        $order = Order::with('user')->where('id', $oid)->first();
        //选择调用的支付接口,从文件缓存里取数据
        $product_base = $this->product_config();
        $product_name = $product_base['appname'];

        $data['ContractNO'] = $this->pinyin_long($product_name).$order->out_trade_no;//合同编号
        $data['AddTime'] = date('Y-m-d H:i:s', $order->created_at->timestamp);//签订日期
        $data['Lender'] = $product_name;//甲方（出借方）
        $data['Borrower'] = $order->user->verify_name;//乙方（借款方）
        $data['BIdenty'] = $order->user->verify_idcard_no;//身份证号
        $data['BMobile'] = $order->user->mobile;//手机号码
        $data['loanTime'] = date('Y-m-d H:i:s', $order->created_at->timestamp);//借款日期
        $data['Principal'] = round($order->real_fee/100, 2);//借款本金
        $data['term'] = $order->days;//借款期限
        $data['Interest'] = round($data['Principal'] * $order->interest/10000 * $data['term'], 2);//利息
        $data['Userfee'] = round($order->change_fee/100, 2);//账户管理费
        $data['repayTime'] = $order->repayment_at;;//应还日期
        $data['repayMoney'] = round($order->total_fee/100, 2) + $data['Interest'];//应还金额
        $data['overFee'] = round($order->default_interest/100, 2);//逾期管理费总额
        return $data;

    }
    //获取汉字首字母
    protected function pinyin_long($zh){  //获取整条字符串所有汉字拼音首字母
        $ret = "";
        $s1 = iconv("UTF-8","GBK//IGNORE", $zh);
        $s2 = iconv("GBK","UTF-8", $s1);
        if($s2 == $zh){$zh = $s1;}
        for($i = 0; $i < strlen($zh); $i++){
            $s1 = substr($zh,$i,1);
            $p = ord($s1);
            if($p > 160){
                $s2 = substr($zh,$i++,2);
                $ret .= $this->getfirstchar($s2);
            }else{
                $ret .= $s1;
            }
        }
        return $ret;
    }
    //获取汉字的首字母
    protected function getfirstchar($s0){
        $fchar = ord($s0{0});
        if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
        $s1 = @iconv("UTF-8",'gb2312//IGNORE', $s0);
        $s2 = @iconv('gb2312',"UTF-8", $s1);
        if($s2 == $s0){$s = $s1;}else{$s = $s0;}
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if($asc >= -20319 and $asc <= -20284) return "A";
        if($asc >= -20283 and $asc <= -19776) return "B";
        if($asc >= -19775 and $asc <= -19219) return "C";
        if($asc >= -19218 and $asc <= -18711) return "D";
        if($asc >= -18710 and $asc <= -18527) return "E";
        if($asc >= -18526 and $asc <= -18240) return "F";
        if($asc >= -18239 and $asc <= -17923) return "G";
        if($asc >= -17922 and $asc <= -17418) return "H";
        if($asc >= -17922 and $asc <= -17418) return "I";
        if($asc >= -17417 and $asc <= -16475) return "J";
        if($asc >= -16474 and $asc <= -16213) return "K";
        if($asc >= -16212 and $asc <= -15641) return "L";
        if($asc >= -15640 and $asc <= -15166) return "M";
        if($asc >= -15165 and $asc <= -14923) return "N";
        if($asc >= -14922 and $asc <= -14915) return "O";
        if($asc >= -14914 and $asc <= -14631) return "P";
        if($asc >= -14630 and $asc <= -14150) return "Q";
        if($asc >= -14149 and $asc <= -14091) return "R";
        if($asc >= -14090 and $asc <= -13319) return "S";
        if($asc >= -13318 and $asc <= -12839) return "T";
        if($asc >= -12838 and $asc <= -12557) return "W";
        if($asc >= -12556 and $asc <= -11848) return "X";
        if($asc >= -11847 and $asc <= -11056) return "Y";
        if($asc >= -11055 and $asc <= -10247) return "Z";
        return NULL;
        //return $s0;
    }
    //获取缓存文件的数据
    protected function product_config(){
        $product_config = new ProductFlockController();
        $product_base = $product_config->read_file();
        return $product_base;
    }
    //前端获取还款页面的选择方法
    public function choose_pay_page(Request $request){
        $rec = $request->all();
        $product_base = $this->product_config();
        $customer = $product_base['pay_method'];
        if($customer == 3){
            $return_url = '';
            return ['code' => 3, 'url' => $return_url];
        }else{
            $return_url = '/html/pay_changjie.html?oid='.$rec['oid'].'&type='.$rec['type'];
            return ['code' => 0, 'url' => $return_url];
        }
    }
    //前端获取展期页面的选择方法
    public function choose_extend_page(Request $request){
        $rec = $request->all();
        $product_base = $this->product_config();
        $customer = $product_base['pay_method'];
        if($customer == 3){
            $return_url = '';
            return ['code' => 3, 'url' => $return_url];
        }else{
            $return_url = '/html/pay_changjie_extend.html?oid='.$rec['oid'];
            return ['code' => 0, 'url' => $return_url];
        }
    }
    //绑卡的页面判断
    public function choose_bindcard_page(){
        $product_base = $this->product_config();
        $customer = $product_base['bankcard'];
        if($customer == 3){
            $return_url = '/html/verify_bankcard_huicao.html';
            return ['code' => 3, 'url' => $return_url];
        }else{
            $return_url = '/html/verify_bankcard.html';
            return ['code' => 0, 'url' => $return_url];
        }
    }
    //签名的生成方法
    public function rsaVerify($postData){
        $rsaVerify_arr = $postData;
        $rsaVerify_arr = array_filter($rsaVerify_arr); //过滤掉空值
        ksort($rsaVerify_arr);
        $rsaVerify_str = '';
        foreach ($rsaVerify_arr as $k => $v)
        {
            if ($rsaVerify_str)
            {
                $rsaVerify_str .= '&' . $k . '=' . $v;
            } else
            {
                $rsaVerify_str = $k . '=' . $v;
            }
        }
        return $rsaVerify_str;
    }
    //注册时渠道是否开启图形验证码
    public function isshow(Request $request){
        $rec = $request->all();
        $cid = $rec['cid'];
        $channel = Channel::withoutGlobalScopes()->where('remark', $cid)->first();
        if(!count($channel)){
            return ['code' => -1, 'text' => '渠道不存在'];
        }
        if($channel->isopencode == 2){
            return ['code' => 0, 'text' => 'open'];
        }
        return ['code' => -1, 'text' => 'close'];
    }
    //重置密码的时候是否开启图形验证码
    public function resetisshow(Request $request){
        $rec = $request->all();
        $mobile = $rec['mobile'];
        $user = User::with('channel')->where('mobile', $mobile)->first();
        if(!count($user)){
            return ['code' => -1, 'text' => '用户不存在'];
        }
        if($user->channel->isopencode == 2){
            return ['code' => 0, 'text' => '请输入图形验证码'];
        }
        return ['code' => 1, 'text' => 'ok'];
    }
    //解绑用户绑定的银行卡
    public function unbind_bankcard(Request $request){
        $is_auth = Admin::user()->inRoles(['admin', 'administrator']);
        if(!$is_auth){
            return ['code' => -1, 'text' => '权限不足'];
        }
        $rec = $request->all();
        $uid = $rec['uid'];
        $user = User::where('id', $uid)->first();

        $product_base = $this->product_config();
        $customer = $product_base['pay_method'];
        $res = [];
        if($customer == 1){//合力宝
            $res = $this->baoheUnbindCard($user['id']);
        }elseif($customer ==  2){//畅捷
            $user_info['id'] = $user['id'];
            $user_info['beforecard'] = substr($user['verify_bankcard_no'], 0, 6);
            $user_info['aftercard'] = substr($user['verify_bankcard_no'], -4);
            $res = $this->unbindCard($user_info);
        }elseif($customer == 4){

        }
        //改变用户状态
        $user->bankcard_ok = 0;
        $user->save();
        $tenant_id = $user->tenant_id;
        $detail = '解绑了'.$user['mobile'].'的银行卡绑定';
        $this->logoperation($request, $detail, $tenant_id);
        return $res;
    }
    //获取用户使用协议
    public function userprotocol(Request $request){
        $mechant = $request->input('tenant_id');
        $product_config = ProductConfig::withoutGlobalScopes()->where('tenant_id', $mechant)->select('useprotocol', 'borrowprotocol', 'promotion_banner')->first();
        return ['code' => 0, 'text' => 'success', 'data' => $product_config];
    }
    //记录操作日志
    public function logoperation($request, $detail, $tenant_id){
        $clientip = $request->getClientIp();
        $log = [
            'user_id' => Admin::user()->id,
            'path'    => substr($request->path(), 0, 255),
            'method'  => $request->method(),
            'ip'      => $clientip,
            'input'   => json_encode($request->input()),
            'detail'  => $detail,
            'tenant_id' => $tenant_id
        ];
        try {
            OperationLogModel::create($log);
        } catch (\Exception $exception) {
            // pass
        }
    }

    //选择风控供应商
    public function chooseRiskType(){
        $type =  GlobalConfig::where('name', 'risktype')->value('value');
        return ['code' => 0, 'risktype' => $type];
    }

    //简易版的银行卡认证
    public function verifyBankCardEasy(Request $request){
        $uid = session('uid');
        $remark = 'verify_bank_card'.$uid;
        $verifyNum = Redis::GET($remark);
        if($verifyNum > 5){
            return ['code' => 1, 'text' => '验证超频，请稍后再试！'];
        }
        Redis::INCR($remark);
        Redis::EXPIRE($remark, 86400);
        $bankcard = $request->input('bankcard');

        if(!$bankcard) return ['code' => 1, 'text' => '银行卡不能为空！'];

        $user = User::withoutGlobalScopes()->where('id', $uid)->first();
        $user->verify_bankcard_no = $bankcard;
        $user->verify_info_date = date('Y-m-d H:i:s');
        $user->bankcard_ok = 1;
        $is_save = $user->save();
        if($is_save){
            return ['code' => 0, 'text' => '银行卡保存成功！'];
        }
        return ['code' => 1, 'text' => '银行卡保存失败！'];
    }

    //linkface银行卡验证
    public function linkfacebindcard(Request $request){
        $uid = session('uid');
        $remark = 'verify_bank_card'.$uid;
        $verifyNum = Redis::GET($remark);
        if($verifyNum > 5){
            return ['code' => 1, 'text' => '验证超频，请稍后再试！'];
        }
        Redis::INCR($remark);
        Redis::EXPIRE($remark, 86400);

        $user = User::select('id','verify_name','verify_idcard_no', 'bankcard_ok')->where('id', $uid)->first();
        if($user['bankcard_ok']) return ['code' => 1, 'text' => '不能重复认证！'];
        $name = $user['verify_name'];
        $idcard = $user['verify_idcard_no'];
        $bankcard = $request->input('bankcard');
        $mobile = $request->input('mobile');
        $postUrl = config('carrier.linkface.verify_bankcard_url');

        $postData = [
            'api_id' => config('carrier.linkface.api_id'),
            'api_secret' => config('carrier.linkface.api_secret'),
            'name' => $name,
            'id_number' => $idcard,
            'card_number' => $bankcard,
            'phone_number' => $mobile
        ];
        try{
            $response = curl_nossl_post($postUrl, $postData);
            @file_put_contents('../storage/logs/linkface_define_bindcard_charge_'.date('Ymd').'.log', date('Y-m-d H:i:s').'||post='.json_encode($postData).'||res='.json_encode($response).'user_id='.$uid.PHP_EOL, FILE_APPEND);
        }catch (\Exception $ex){
            @file_put_contents('../storage/logs/linkface_define_bindcard_charge_err'.date('Ymd').'.log', date('Y-m-d H:i:s').'||err='.$ex->getMessage().PHP_EOL, FILE_APPEND);
        }
       //扣费,接通jcz
        $send_url = env('OTHER_API').'/api/bindCard';
        $params = [
            'form_params' => [
                'sign' => env('SIGN'),
                'uid' => $uid,
            ]
        ];
        try{
            $res = $this->guzzle($send_url, $params);
            $jcres = json_decode($res->getBody()->getContents(), true);
            if($jcres['code']) return ['code' => 1, 'text' => '商户余额不足！'];
            @file_put_contents('../storage/logs/linkface_define_bindcard_charge_'.date('Ymd').'.log', date('Y-m-d H:i:s').'||post='.$params.'||res='.json_encode($response).'user_id='.$uid.PHP_EOL, FILE_APPEND);
        }catch (\Exception $ex){
            @file_put_contents('../storage/logs/linkface_defined_bindcard_exception_'.date('Ym').'.log', $ex->getMessage().'||user_id='.$uid.'||date='.date('Y-m-d H:i:s'), FILE_APPEND);
            return ['code' => 1, 'text' => '服务器异常，认证失败!'];
        }

        if(isset($response['result']) && $response['result'] == 1){
            //改变状态
            $user->bankcard_ok = 1;
            $user->verify_bankcard_no = $bankcard;
            $user->verify_bankcard_mobile = $mobile;
            $user->bank_name = $response['bank_info']['bank_name'];

            $user->save();
            return ['code' => 0, 'text' => '认证成功！'];
        }else{
            if(isset($response['result'])){
                $resultErrorInfo = $this->linkfaceBankCode($response['result']);
            }else{
                $resultErrorInfo = $response['status'];
            }
            return ['code' => 1, 'text' => $resultErrorInfo];
        }
    }
    //linkface的银行卡认证返回的状态码转化
    protected function linkfaceBankCode($code){
        $result = [
            2 => '不匹配',
            30 => '未开通无卡支付',
            31 => '此卡被没收',
            32 => '无效卡号',
            33 => '此卡无对应发卡行',
            34 => '此卡未初始化或睡眠卡',
            35 => '作弊卡、吞卡',
            36 => '此卡已挂失',
            37 => '此卡已过期',
            38 => '密码错误次数超限',
            39 => '发卡行不支持此交易，请联系发卡行',
            40 => '受限制的卡，建议换卡操作'
        ];
        return $result[$code];
    }

    //留言反馈
    public function feedback(Request $request){
        $mobile = session('mobile');
        if(!$mobile) return ['code' => 1, 'text' => '未登录'];
        $feed = $request->input('textarea');
        $tenant_id = $request->input('merchant');
        if(!$feed) return ['code' => 1, 'text' => '不能为空'];
        //阻止按钮的过分提交
        $isHasSub = CommonController::comRedis('feed_submit_'.$mobile, 5);
        if(!$isHasSub){
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        
        $feedback = new Feedbacke();
        $feedback->mobile = $mobile;
        $feedback->feed = $feed;
        $feedback->tenant_id = $tenant_id;
        $feedback->created_at = date('Y-m-d H:i:s');
        $is_save = $feedback->save();
        if($is_save){
            return ['code' => 0, 'text' => '提交成功'];
        }
        return ['code' => 1, 'text' => '提交失败'];
    }

    //获取所有的反馈
    public function getFeedBack(Request $request){
        $mobile = session('mobile');
        $merchant = $request->input('merchant');
        $feedback = Feedbacke::withoutGlobalScopes()
            ->where('mobile', $mobile)
            ->where('tenant_id', $merchant)
            ->orderBy('id', 'desc')
            ->get();
        return ['code' => 0, 'data' => $feedback];
    }

    //获取申请的配置项
    public function getProductConfig(){
        $uid = session('uid');
        $user = User::withoutGlobalScopes()->where('id', $uid)->first();
        $productConfig = ProductConfig::withoutGlobalScopes()->select(
            'id', 'tenant_id','verify_radio','verify_box','carrier_radio','carrier_box','bankcard_radio','bankcard_box','pay_radio','pay_box','baseinfo_radio','baseinfo_box'
        )->where('tenant_id', $user->tenant_id)->first();
        return ['code' => 0, 'data' => $productConfig];
    }

    //微信和支付宝的数据保存
    public function saveWeizhifubao(Request $request){
        $input = $request->input();
        $uid = session('uid');
        $user = User::withoutGlobalScopes()->where('id', $uid)->first();
        if(!$input['verify_pay_weixin'] && !$input['verify_pay_zhifubao']) return ['code' => 1, 'text' => '两者不能同时为空'];
        $user->verify_pay_weixin = $input['verify_pay_weixin'] ?? '';
        $user->verify_pay_zhifubao = $input['verify_pay_zhifubao'] ?? '';
        $user->verify_bankcard_no = $input['verify_bankcard_no'] ?? '';
        $user->verify_pay_ok = 1;
        $user->bankcard_ok = 1;
        $user->verify_info_date = date('Y-m-d H:i:s');
        $is_save = $user->save();
        if($is_save){
            return ['code' => 0, 'text' => '保存成功'];
        }
        return ['code' => 1, 'text' => '保存失败'];
    }

    /**
     * @param Request $request
     * @return mixed
     *  更新用户通话记录
     */
    public function updateCalllog(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $mobile = session("mobile");
        $phone_contacts = $request->input('phone_calllog','');
        $contacts_arr = json_decode($phone_contacts,true);

        if(!empty($mobile)) {
            if(empty($contacts_arr) || !is_array($contacts_arr)) {
                $return['text'] = '通话记录不能为空';
                return $return;
            }
            
            User::withoutGlobalScopes()->where("mobile","=",$mobile)->update(['call_log' => json_encode($contacts_arr)]);

            $return['code'] = 200;
            $return['text'] = '更新成功';
        }
        return $return;
    }
}
?>